<template>
  <div class="app-container">
    <mobileManage v-if="$store.state.mobile.userAgent==='mobile'"></mobileManage>
    <template v-else>
      <!-- 表单管理 -->
      <div v-show="!showForm" class="formManage" style="height: 100%">
        <div v-if="tableShow"  style="display: flex;height: 100%">
          <!-- 左侧树 -->
         <div v-if="rightConfig.panelType==='left'||rightConfig.panelType==='left-data'" class="treePart">
            <div class="treeList">
              <div class="title">{{rightConfig.leftConfig.title}}</div>
              <div v-show="rightConfig.leftConfig.datasource">  <!-- 选项数据来源之后 才显示树形 -->
                <div style="margin:10px 0px;">
                    <el-input placeholder="请输入关键字" clearable size="small" prefix-icon="el-icon-search" v-model="treeKeyword"></el-input>
                </div>
                <div v-loading="leftTreeLoading">
                    <el-tree :data="treeData" :props="defaultProps" :filter-node-method="filterNode" ref="tree"
                    :expand-on-click-node="false" default-expand-all :highlight-current="true" @node-click="handleNodeClick">
                    </el-tree>
                </div>
              </div>
            </div>
          </div>
           <div :style="{width: (rightConfig.panelType==='left'||rightConfig.panelType==='left-data' ? 'calc(100% - 225px)' : '100%'),padding: (rightConfig.panelType==='left'||rightConfig.panelType==='left-data' ? '0 0 0 20px' : '0')}">
            <!-- 数据面板 -->
            <div v-if="rightConfig.panelType==='data'||rightConfig.panelType==='left-data'" class="card-panel-group">
              <div class="card-panel" :style="{background:item.backColor}"
                v-for="(item, index) in rightConfig.panelConfig" :key="index">
                <div class="card-panel-icon-wrapper icon-people">
                  <svg-icon :icon-class="item.icon" class-name="card-panel-icon"
                    :style="{color:item.iconColor,background:item.iconBackColor}" />
                </div>
                <div class="card-panel-description">
                  <span class="card-panel-num">{{panelValues[index]}}</span>{{item.unit}}
                  <div class="card-panel-text">
                    {{item.title}}
                  </div>
                </div>
              </div>
            </div>
            <div>
            <!-- 搜索栏 -->
            <el-form inline :model="searchForm" ref="searchForm" v-if="searchBox" class="searchContent" style="display:inline">
              <el-form-item v-for="(item, index) in searchData" :key="index" :label="item.type==='data'?!['signature'].includes(item.searchTag)?item.name:'':'创建时间'">
                <template v-if="item.type === 'data'">
                  <my-select :value="searchForm[item.value]" v-if="(item.searchTag === 'my-select' &&item.tag !== 'coding' ) || item.searchTag === 'my-radio-group'" :options="item.options" :tableName="item.tableName" 
                  :dataType="item.dataType" :fieldName="item.fieldName" :dictName="item.dictName" @input="handlerCommonValue($event,item.value)"></my-select>
                 <my-cascader :value="searchForm[item.value]" :fields="item.fields" :options="item.options" v-else-if="item.searchTag === 'my-cascader'" :dataType="item.dataType" @input="handlerCommonValue($event,item.value)"></my-cascader>
                 <my-select :value="searchForm[item.value]" :multiple="true" v-else-if="item.searchTag === 'my-checkbox-group'" :options="item.options" :tableName="item.tableName" 
                  :dataType="item.dataType" :fieldName="item.fieldName" :dictName="item.dictName" @input="handlerCommonValue($event,item.value)"></my-select>
                  <el-select v-else-if="item.tag === 'switch'" v-model="searchForm[item.value]"
                    :placeholder="`请选择${item.name}`" clearable>
                    <el-option key="true" label="是" :value="item.options[0]"></el-option>
                    <el-option key="false" label="否" :value="item.options[1]"></el-option>
                  </el-select>
                  <el-date-picker v-else-if="item.tag==='date-range'" v-model="searchForm[item.value]" size="small" type="daterange"
                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                    value-format="yyyy-MM-dd" format="yyyy-MM-dd">
                  </el-date-picker>
                  <el-time-picker v-else-if="item.tag == 'time-range'"  is-range v-model="searchForm[item.value]"  range-separator="至"
                        start-placeholder="开始时间"  end-placeholder="结束时间" value-format="HH:mm:ss">
                  </el-time-picker>
                  <!--时间选择 可是范围 可是精确-->
                  <el-time-picker v-else-if="item.tag == 'time' && item.searchType == 'between'"  is-range v-model="searchForm[item.value]"  range-separator="至"
                        start-placeholder="开始时间"  end-placeholder="结束时间" value-format="HH:mm:ss">
                  </el-time-picker>
                  <!--日期选择 可是范围 可是精确  年没有范围选择--> 
                  <el-date-picker v-else-if="item.tag==='date' && item.searchType == 'between'" v-model="searchForm[item.value]" size="small" :type="item.dataPickerType === 'year' ?item.dataPickerType : item.dataPickerType+'range'"
                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                    :value-format="item.valueFormat" :format="item.valueFormat">
                  </el-date-picker>

                  <el-time-picker v-else-if="item.tag == 'time'" v-model="searchForm[item.value]"  format='HH:mm:ss' value-format="HH:mm:ss"
                    :picker-options="{
                        selectableRange: '00:00:00-23:59:59'
                      }"  placeholder="请选择">
                  </el-time-picker>
                  <el-date-picker v-else-if="item.tag == 'date'" v-model="searchForm[item.value]" :type="item.dataPickerType" :value-format="item.valueFormat"
                    :format="item.valueFormat" placeholder="请选择">
                  </el-date-picker>
                  <el-slider v-else-if="item.tag == 'slider'" style="width:200px" v-model="searchForm[item.value]"></el-slider>
                  <el-rate v-else-if="item.tag == 'rate'" v-model="searchForm[item.value]"></el-rate>
                  <el-color-picker v-else-if="item.tag == 'color'" v-model="searchForm[item.value]"></el-color-picker>
                  <el-select v-else-if="item.tag == 'user'" filterable  v-model="searchForm[item.value]" placeholder="请选择用户" @visible-change="getusersearch">
                      <el-option v-for="userval in allUserList" :key="userval.id" :label="`${userval.nickname}/${userval.username}`" :value="userval.id"></el-option>
                    </el-select>
                    <el-select v-else-if="item.tag == 'post'" filterable  v-model="searchForm[item.value]" placeholder="请选择岗位" @visible-change="getpostsearch">
                      <el-option v-for="postval in allPostList" :key="postval.code" :label="postval.name" :value="postval.id"></el-option>
                    </el-select>
                    <el-select v-else-if="item.tag == 'depart'" filterable  v-model="searchForm[item.value]" placeholder="请选择部门" @visible-change="getdeptsearch">
                      <el-option v-for="deptval in departAllList" :key="deptval.id" :label="deptval.name" :value="deptval.id"></el-option>
                    </el-select>
            
                  
                  <el-tree-select :value="searchForm[item.value]" v-else-if="item.searchTag == 'el-tree-select'" :options="item.options" :fields="[]" :dataType="item.dataType" @input="handlerCommonValue($event,item.value)"></el-tree-select>
                  <get-map-point :value="searchForm[item.value]" v-else-if="item.tag == 'place'" @input="handlerCommonValue($event,item.value)"></get-map-point>
                  <my-region :value="searchForm[item.value]" v-else-if="item.searchTag == 'my-region'" @input="handlerCommonValue($event,item.value)"></my-region>
                  <el-input v-else-if="item.tag == 'number' || item.tag == 'numbers'" v-model="searchForm[item.value]" :placeholder="`请输入${item.name}`"></el-input>
                  <el-input v-else-if="item.tag==='upload'" v-model="searchForm[item.value]" :placeholder="`请输入文件名称`" clearable
                    size="small">
                  </el-input>
                  <el-input v-else-if="!['signature'].includes(item.searchTag)" v-model="searchForm[item.value]" :placeholder="`请输入${item.name}`" clearable
                    size="small">
                  </el-input>
                </template>
                <template v-else>
                  <el-date-picker v-if="item.value==='createTime'" v-model="datetime" size="small" type="datetimerange"
                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                    value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                  <!-- <el-input v-else-if="item.value==='creator'" v-model="searchForm[item.value]"
              :placeholder="`请输入创建者`" clearable size="small">
            </el-input> -->
                  <!-- <el-date-picker v-else-if="item.value==='updateTime'" v-model="datetimeUpdate"
              size="small" type="datetimerange" range-separator="至" start-placeholder="修改开始日期" end-placeholder="修改结束日期"
              value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker> -->
                </template>
              </el-form-item>
               <el-form-item label="流程状态" v-if="showApproval">
                  <el-select v-model="processStatus" placeholder="请选择流程状态" clearable>
                    <el-option v-for="dict in processStateList"
                              :key="dict.value" :label="dict.label" :value="dict.value"/>
                  </el-select>
                </el-form-item>
              <el-form-item v-if="searchData.length>0" style="marginTop: -2px">
                <el-button type="primary" @click="searchChange" style="marginLeft:10px;" size="small" icon="el-icon-search">搜索</el-button>
                <el-button @click="searchReset" style="marginLeft:10px;" size="small" icon="el-icon-refresh">重置</el-button>
              </el-form-item>
            </el-form>
            <div class="operationColumn">
              <span v-for="(item, btnIdx) in tableBtn" :key="btnIdx">
                  <!-- <el-button style="margin-right:10px" v-if="item.label==='发起审批'&&showApproval" :disabled="canClick(item.label)"
                    @click="approvalData('',item.position)" :type="item.type" size="small">{{item.text}}</el-button> -->
                  <template v-if="item.label==='导入'">
                      <el-tooltip effect="dark" content="请通过模板导入，且勿更改模板结构" placement="top-start">
                        <el-button style="margin-right:10px" @click="importData" size="small" :type="item.type">{{item.text}}
                        </el-button>
                      </el-tooltip>
                  </template>
                  <el-button style="margin-right:10px" v-else-if="item.label==='新增'" @click="insertData" :type="item.type"
                    size="small" icon="el-icon-plus">{{item.text}}</el-button>
                  <template v-else-if="item.label==='批量操作'">
                    <el-dropdown placement="bottom-end" style="margin-right:100px" @command="handleCommand" trigger='click' ref="messageDrop">
                      <el-button @click="clickBtn" size="small">{{item.text}}<i class="el-icon-arrow-down el-icon--right"></i></el-button>
                      <el-dropdown-menu slot="dropdown">
                        <el-cascader-panel :options="optionsCascader" v-model="valueCascader" ref="csacadersVisible" @change="handleChange"></el-cascader-panel>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                  <!-- <el-button v-else-if="item.label==='批量删除'" :disabled="multipleSelection.length===0" @click="multiDel" :type="item.type" size="small">{{item.text}}</el-button> -->
                  <el-button style="margin-right:10px" v-else-if="item.label!=='发起审批'" @click="operateData('',item.position,item.label)"
                    :type="item.type" size="small" :disabled="canClick(item.label)">{{item.text}}</el-button>
                </span>
                <el-popover
                  placement="bottom"
                  width="400" style="margin-right: 10px"
                  v-if="outerChain"
                  trigger="click">
                  <div>
                    <div>
                      表单链接：<span>{{formPath}}</span>
                    </div>
                    <div style="display: flex;margin-top:10px;">
                      二维码： <QRCodeView :text="formPath"></QRCodeView>
                    </div>
                  </div>
                  <el-button slot="reference">表单链接</el-button>
                </el-popover>
                <el-button @click="getHistoryList" type="danger" size="small" v-if="showApproval">历史记录</el-button>
                <el-tooltip class="item" effect="dark" content="显隐" placement="top">
                  <el-button icon="el-icon-s-operation" circle @click="drawer = true"></el-button>
                </el-tooltip>
            </div>
           </div>
            <el-table id="out-table" :data="tableData" stripe size="small" highlight-current-row default-expand-all border
              @selection-change="handleSelectionChange" v-loading="tableLoading" :row-key="row => { return row.id }"
              ref="multipleTable" style="width:100%;height:50" v-if="tableShow" class="tableInfo" @sort-change="changeSort"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              @select-all="selectAllFun" 
              @select="selectFun"
              :row-class-name="rowClassNameFun"
              :header-row-class-name="headerRowClassName"
              :span-method="mergeSpanMethod"
            >
              <template v-if="showTemplate">
                <el-table-column type="selection" width="50" align="center" :reserve-selection="true"
                  :fixed="rightConfig.colConfig.leftCol>0?'left':false">
                </el-table-column>
                <el-table-column :label="rightConfig.colConfig.indexName" :width="rightConfig.colConfig.indexSize" align="center"
                  :fixed="rightConfig.colConfig.leftCol>1?'left':false"
                  v-if="showHideData.length>0&&rightConfig.colConfig.showIndex&&!showHideData[0].hide && rightConfig.panelType !=='grouping'">
                  <template slot-scope="scope">
                    <span>{{formatIndex(scope.$index)}}</span>
                  </template>
                </el-table-column>
              </template>
                <template v-for="(item,index) in fieldData"> 
                    <el-table-column  v-if="rightConfig.colConfig.showIndex ? !(showHideData[index + 1]&&showHideData[index + 1].hide) : !(showHideData[index] && showHideData[index].hide)" :key="index" :prop="item.value" :label="item.name" :align="item.children ? 'center' : item.align"
                      :width="item.width" show-overflow-tooltip
                    :sortable="item.sorting?'custom':false" :fixed="getFixed(index)">
                    <template slot-scope="scope">
                        <span v-if="item.format==='datetime' && item.tag!=='date'">{{getDateTime(scope.row[item.value])}}</span>
                        <span
                            v-else-if="specialTypes.includes(item.tag)">{{getShowValue(scope.row[item.value],item.tag,item.dataType,item.options, item.value)}}
                        </span>
                        <span v-else-if="item.tag==='color'">
                            <span
                            :style="{background:scope.row[item.value],width:'10px',height:'10px',display:'inline-block'}"></span>
                            {{scope.row[item.value]}}
                        </span>
                        <span v-else-if="item.tag==='upload'">{{getFileNames(scope.row[item.value])}}</span>
                        <span v-else-if="item.tag==='password'">{{getPassword(scope.row[item.value])}}</span>
                        <span v-else-if="item.tag==='rich-text'">{{getTinymce(scope.row[item.value])}}</span>
                        <span v-else-if="item.tag==='depart'">{{getNameById(scope.row[item.value])}}</span>
                        <span v-else-if="item.name.indexOf('身份证') != -1">{{encryptCert(scope.row[item.value])}}</span>
                        <span v-else-if="item.tag==='email' || item.tag==='tuwen'">{{scope.row[item.value]===''?'':'图片'}}</span>
                        <span v-else-if="item.tag==='number' || item.tag === 'numbers'">{{getNumber(scope.row[item.value])}}</span>
                        <span v-else>{{scope.row[item.value]}}</span>
                    </template>
                    <el-table-column v-for="(secondItem, secondIdx) in item.children" :key="secondIdx" :prop="secondItem.value" :label="secondItem.name" :show-overflow-tooltip="!hiddenOperating" align="center">
                        <template slot-scope="secondScope">
                            <span v-if="secondItem.format==='datetime' && secondItem.tag!=='date'">{{getDateTime(secondScope.row[secondItem.value])}}</span>
                            <span
                                v-else-if="specialTypes.includes(secondItem.tag)">{{getShowValue(secondScope.row[secondItem.value],secondItem.tag,secondItem.dataType,secondItem.options)}}
                            </span>
                            <span v-else-if="secondItem.tag==='color'">
                                <span
                                :style="{background:secondScope.row[secondItem.value],width:'10px',height:'10px',display:'inline-block'}"></span>
                                {{secondScope.row[secondItem.value]}}
                            </span>
                            <span v-else-if="secondItem.tag==='upload'">{{getFileNames(secondScope.row[secondItem.value])}}</span>
                            <span v-else-if="secondItem.tag==='password'">{{getPassword(secondScope.row[secondItem.value])}}</span>
                            <span v-else-if="secondItem.tag==='rich-text'">{{getTinymce(secondScope.row[secondItem.value])}}</span>
                            <span v-else-if="secondItem.tag==='depart'">{{getNameById(secondScope.row[secondItem.value])}}</span>
                            <span v-else-if="secondItem.tag==='email' || secondItem.tag==='tuwen'">{{secondScope.row[secondItem.value]===''?'':'图片'}}</span>
                            <span v-else-if="secondItem.tag==='number' || secondItem.tag === 'numbers'">{{getNumber(secondScope.row[secondItem.value])}}</span>
                            <span v-else>{{secondScope.row[secondItem.value]}}</span>
                        </template>
                        <el-table-column v-for="(thirdItem, thirdIdx) in secondItem.children" :key="thirdIdx" :prop="thirdItem.value" :label="thirdItem.name" show-overflow-tooltip align="center">
                            <template slot-scope="thirdScope">
                                <span v-if="thirdItem.format==='datetime' && thirdItem.tag !=='date'">{{getDateTime(thirdScope.row[thirdItem.value])}}</span>
                                <span
                                    v-else-if="specialTypes.includes(thirdItem.tag)">{{getShowValue(thirdScope.row[thirdItem.value], thirdItem.tag, thirdItem.dataType, thirdItem.options)}}
                                </span>
                                <span v-else-if="thirdItem.tag==='color'">
                                    <span
                                    :style="{background:thirdScope.row[thirdItem.value],width:'10px',height:'10px',display:'inline-block'}"></span>
                                    {{thirdScope.row[thirdItem.value]}}
                                </span>
                                <span v-else-if="thirdItem.tag==='upload'">{{getFileNames(thirdScope.row[thirdItem.value])}}</span>
                                <span v-else-if="thirdItem.tag==='password'">{{getPassword(thirdScope.row[thirdItem.value])}}</span>
                                <span v-else-if="thirdItem.tag==='rich-text'">{{getTinymce(thirdScope.row[thirdItem.value])}}</span>
                                <span v-else-if="thirdItem.tag==='depart'">{{getNameById(thirdScope.row[thirdItem.value])}}</span>
                                <span v-else-if="thirdItem.tag==='email' || thirdItem.tag==='tuwen'">{{thirdScope.row[thirdItem.value]===''?'':'图片'}}</span>
                                <span v-else-if="thirdItem.tag==='number' || thirdItem.tag === 'numbers'">{{getNumber(thirdScope.row[thirdItem.value])}}</span>
                                <span v-else>{{thirdScope.row[thirdItem.value]}}</span>
                            </template>
                        </el-table-column>
                    </el-table-column>
                </el-table-column>
                </template>
                <template v-if="showTemplate">
                  <el-table-column prop="create_time" label="创建时间" align="center" min-width="160" show-overflow-tooltip
                    v-if="showCreateTime"
                    :fixed="((rightConfig.colConfig.rightCol===2&&!showApproval) || rightConfig.colConfig.rightCol>2 )?'right':false">
                    <template slot-scope="scope">{{getDateTime(scope.row.create_time)}}</template>
                  </el-table-column>
                  <el-table-column v-if="showColFunc"
                    prop="result" label="流程状态" align="center" show-overflow-tooltip
                    :fixed="rightConfig.colConfig.rightCol>1?'right':false">
                    <template slot-scope="scope">
                    <el-tag
                        :type="scope.row.result=='1' ? '': scope.row.result=='2' ? 'success' : scope.row.result=='3' ? 'danger': scope.row.result=='4' ? '': 'info'">
                         {{resultFmt(scope)}}
                    </el-tag>
                    </template>
                  </el-table-column>
                </template>
              <el-table-column v-if="!hiddenOperating && timeStamp" label="操作" align="center" :fixed="rightConfig.colConfig.rightCol>0?'right':false" width="252">
                <template slot-scope="scope" v-if="(rightConfig.panelType==='grouping'&& !scope.row.children) || rightConfig.panelType!=='grouping'">
                    <div v-if="!showApproval" style="display:flex;justify-content:center;">
                        <span v-for="(item, tempIdx) in lineBtnList" :key="tempIdx+'-item'">
                            <div v-if="lineBtn.length > 2">
                               <el-button class="btnClassCss" 
                                @click="operateData(scope.row,item.position,item.label)" type="text" size="small">
                              <el-link :type="item.type">{{item.text}}</el-link>
                              </el-button>
                            </div>
                          </span>
                          <span v-for="(item, tempIdx) in lineBtn" :key="tempIdx">
                            <div v-if="lineBtn.length < 3">
                               <el-button class="btnClassCss" 
                                @click="operateData(scope.row,item.position,item.label)" type="text" size="small">
                              <el-link :type="item.type">{{item.text}}</el-link>
                              </el-button>
                            </div>
                          </span>
                           <el-dropdown trigger="click" v-if="lineBtn.length > 2" style="margin-top:2px;font-size: 12px">
                            <span class="el-dropdown-link">
                              更多<i class="el-icon-arrow-down el-icon--right"></i>
                            </span>
                            <el-dropdown-menu slot="dropdown">
                               <span v-for="(item, tempIdx) in dropList" :key="tempIdx">
                                   <el-dropdown-item
                                    @click.native="operateData(scope.row,item.position,item.label)"
                                    >{{item.label}}</el-dropdown-item
                                  >
                               </span>
                            </el-dropdown-menu>
                          </el-dropdown>
                          <el-button class="btnClassCss" size="small" type="text" v-if="!(lineBtn.length>0 )" disabled>暂无操作</el-button>
                    </div>
                    <div v-if="showApproval">
                      <span v-for="(item, tempIdx) in lineBtn" :key="tempIdx+'-item'">
                        <el-button size="small" type="text" @click="operateData(scope.row,'inline','查看');"  v-if= "item.label === '查看'" style="margin-left: 10px;">
                            <el-link type="primary">{{item.text}}</el-link>
                        </el-button>
                            <el-button size="small" type="text" @click="operateData(scope.row,'inline','编辑')" v-if="[4,5].includes(scope.row.result)  && item.label === '编辑'" style="margin-left: 10px;">
                            <el-link type="primary">{{item.text}}</el-link>
                        </el-button>
                        <el-button size="small" type="text" @click="operateData(scope.row,'inline','删除')" v-if="[4,5].includes(scope.row.result) && item.label === '删除'" style="margin-left: 10px;">
                            <el-link type="primary">{{item.text}}</el-link>
                        </el-button>
                            <el-button size="small" type="text" @click="approvalData(scope.row,'inline')" v-if="[4,5].includes(scope.row.result) && item.label === '发起审批'" style="margin-left: 10px;">
                            <el-link type="primary">{{item.text}}</el-link>
                        </el-button>
                        <el-button size="small" type="text" @click="changePass(scope.row)" v-if="scope.row.result === 2 && lineBtn.filter((_) => _.label == '变更').length ==1 && item.label === '变更'" style="margin-left: 10px;">
                            <el-link type="primary">{{item.text}}</el-link>
                        </el-button>
                        <el-button size="small" type="text" @click="withdrawData(scope.row)" v-if="scope.row.result === 1 && item.label === '撤回'" style="margin-left: 10px;">
                            <el-link type="primary">{{item.text}}</el-link>
                        </el-button>
                      </span>
                    </div>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination background :layout="layout" :total="total" :page-size="page.pageSize" :page-sizes="pageSizes"
              :current-page="page.pageNo" style="float:right;marginTop:20px;marginBottom:20px;" @size-change="sizeChange"
              @current-change="currentChange" v-if="pagination && rightConfig.panelType !== 'tree-list'">
            </el-pagination>
          </div>
        </div>
      </div>
      <!-- 表单新增、编辑、预览页面/弹窗 -->
      <div v-show="showForm">
        <template v-if="formConfData.formType==='msgBox'">
          <el-dialog :title="title" :visible.sync="dialogVisible" :style="{marginTop:`${dialogTop} !important`}" :class="dialogTop ? 'delmarginTop' : ' '"
            :width="dialogWidth" @close="()=>{showForm = false}">
            <div style="display:flex;justifyContent:center;">
              <parser :form-conf="formConfData" :tableName="tableName" :status="status" :key="time" :originData="originData" v-if="showForm" @submit="submit"
                @loadingPae="submitLoading = true" style="width:95%;" @cancel="()=>{dialogVisible = false}" @reset="reset" ref="msgBoxParser" :codeReshow ="codeReshow"/>
            </div>
          </el-dialog>
        </template>
        <template v-else>
          <div class="editTitle">
            <el-button type="primary" @click="closeForm" style="marginLeft:10px;float:right;">返回</el-button>
            <span style="fontSize:18px;">{{formName + '--' + title}}</span>
                <span style="float:right;" v-if="showStepBtn">
                    <el-button icon="el-icon-arrow-left" @click="jumpStepBtn('down')" size="small">{{up}}</el-button>
                    <el-button v-if="!showSumbit" @click="jumpStepBtn('up')" size="small">{{down}}<i class="el-icon-arrow-right el-icon--right"></i></el-button>
                    <el-button v-if="showSumbit"  @click="sumbitSeps()" size="small" type="primary">{{sumbitBtn}}</el-button>
                    <el-button @click="closeForm" size="small">{{finish}}</el-button>
                </span>
          </div>
          <div style="display:flex;justifyContent:center;" v-loading="submitLoading">
            <!-- <parser :form-conf="formConfData"  v-if="showForm" @submit="submit"
              style="width:80%;"  @cancel="()=>{showForm=false}" @reset="reset"/> -->
            <parser ref="parserRef" v-if="showForm" :form-conf="formConfData" :tableName="tableName" :status="status" :originData="originData"
              @cancel="closeForm"  @submit="submit" @loadingPae="submitLoading = true" @change="changeSumbit"
			  style="width:100%;"
              @click='drawerClick' :showHideData='showHideData' :key="time" @reset="reset" :codeReshow ="this.codeReshow"/>
          </div>
        </template>
      </div>
      <!-- 列显隐 -->
      <el-drawer :visible.sync="drawer" direction="rtl">
        <span slot="title" style="fontSize:18px;font-weight:500;color: #262626;">列显隐</span>
        <el-table :data="showHideData" size="small" border style="width:80%;marginLeft:10%;">
          <el-table-column prop="columnName" label="列名" align="center">
          </el-table-column>
          <el-table-column prop="hide" label="隐藏" align="center">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.hide"></el-checkbox>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
      <div v-if="showImportDialog">
          <TableDataImportDialog :curFormId="tableName" :curFormName="this.formConfData.formName" @closeDialog="closeTableDialog">
          </TableDataImportDialog>
      </div>
      <div v-if="showHistroyDialog">
        <viewBpmDialog @closeBpmDialog="() => showHistroyDialog = false" :processId="processDefinitionId" :processInstanceId="processInfoId" :fieldDataHview="fieldData" 
          :tableDataOriginal="tableDataOriginal" :rightConfigHview="rightConfig" :treeKeyAndLabelMapHview="treeKeyAndLabelMap" :tableNameHview="tableName"></viewBpmDialog>
      </div>
    </template>
  </div>
</template>
<script>
  import {getComputeFieldNew} from '@/api/custom/portalDesigner';
  import { reorganizationParam } from '@/utils/index'
  import mobileManage from '../mobiledesign/mobileComponents/mobileManage'
  import viewBpmDialog from './viewBpmDialog.vue'
  import QRCode from 'qrcodejs2'
  import QRCodeView  from '@/components/qrView'
  import {
    getPageNoRelease,
    getPageRelease,
    delFormInfo,
    insertdata,
    updata,
    getDataOneId,
    deletedata,
    deletedataAll,
    getListData,
    menuRelease,
    getAllListData,
    getIdsData,
    getVesDataPoc,
    getVesDataPocAll,
    isNullFile,
    getProcessIn,
    deleteExampleData,
    getFormulaValue,
    insertdatalist,
    getChildListData,
    updatedatalist,
    insertdataall,
    updataall,
    batchCreate,
    getDataOut
  } from "../../../api/custom/formPoster";
  import {
    getFormInfo,
    getColumnData,
    getDictData,
    getBtnInfo,
    geDeptList,
    insertData,
    sourceTestList,
    getUserList,
    gePostList
  } from '@/api/custom/formDesigner'
  import {
    createProcessInstance,
    cancelProcessInstance
  } from "@/api/bpm/processInstance";
  import {
    listSimpleDepts
  } from '@/api/system/dept';
  import Parser from '../formdesign/components/parser'
//   import XLSX from '@/utils/xlsx.core.min.js'
  import Cookies from "js-cookie";
  import { regionData } from "element-china-area-data";
  import {getAccessToken} from '@/utils/auth'
  import TableDataImportDialog from '../formdesign/components/TableDataImportDialog.vue'
import { deepClone, param } from '../../../utils';
import { bindEventScript } from '@/utils/event-script'
import FileSaver from 'file-saver'
import * as XLSX from "xlsx";
import {
  listUser,
} from "@/api/system/user";
import { listPost } from "@/api/system/post";
import table2excel from './table-excel';
import { getProcessDetailPath } from "@/utils/micro";
const arrTypes = ['cascader', 'checkbox', 'time-range', 'date-range', 'user','post','depart','tree-table']; //组件返回数组
const specialTypes = ['switch', 'cascader', 'select', 'radio', 'checkbox','tree-table', 'tree', 'depart']; //需处理后在table中展示
const basicTypes = ['number', 'color', 'rate', 'date', 'time', 'password', 'textArea', 'input', 'slider','place', 'numbers']; //从数据库中获取值无需处理

  export default {
    name: 'formmanage',
    components: {
      Parser,
      TableDataImportDialog,
      mobileManage,
      viewBpmDialog,
      QRCodeView
    },
    data() {
      return {
        showSumbit: false, //显示完成
        codeReshow:{},//编码组件编辑，查看，变更存值
        allUserList: [],
        allPostList: [],
		processStatus: '', //流程状态
        searchFormData: {},
		    lineBtnList: [],
        dropList: [],
        regionDataCopy: regionData,
        groupArray:[], //分组列表批量操作时选中数据
        treeArray:[],
        hiddenOperating: false,
        // uploadField:[],//需要下载附件的字段
        backFields:[],//批量下载时往后端传的数据数组
        valueCascader: [],  //级联选中选项
        optionsCascader:[], //级联所有选项
        isImage:false,//判断是否是图片类型
        showHistroyDialog: false,
        isAllTreeSelect: false,
        checkedKeys: false, //识别全选框是否被选中，默认为未被选中；
        treeNodeId: '', //点击树节点id
        time:'', //parser的key值
        showApproval: false, //是否关联流程
        formId: '', //表单Id
        showForm: false, //表单新增、编辑、查看页面
        drawer: false, //列显隐抽屉
        formJsonMessage: {}, //表格配置
        tableName: '', //表名
        formName: '', //表单名
        outerChain: false, // 是否显示外链
        searchForm: {}, //顶部搜索
        tableData: [], //表数据
        tableDataOriginal: [], // 原始tableData数据
        treeTableOptions: [], // 拷贝表数据
        specialTypes: specialTypes, //特殊类型组件
        searchData: [], //搜索配置
        listData: [], //列配置
        fields: [], //字段
        fieldData: [], //字段
        showHideData: [], //列显隐
        total: 0, //总数
        layout: "total,prev, pager, next,sizes,jumper", //分页显示布局
        pageSizes: [10, 20, 30, 50], //分页显示每页条数选择
        page: {
          pageNo: 1,
          pageSize: 10
        },
        departMap: new Map(),
        pagination: true, //是否分页
        order: '',  //是否排序
        fieldName: '', //排序字段
        oldorder: '', //是否排序
        oldfieldName: '', //排序字段
        dialogTop: '20%', //弹窗距顶部高度
        dialogWidth: '500px', //弹窗宽度
        datetime: [], //创建时间搜索
        // datetimeUpdate: [],  //修改时间搜索
        tableLoading: false, //加载表格数据
        tableShow: false, //显示表格
        multipleSelection: [], //表格多选
        formConfData: {}, //表单配置json
        originData: {}, //表单原始数据
        title: '新增', //弹窗标题
        status: '', //状态标识，新增add,查看view,编辑edit,变更change
        dialogVisible: false, //弹窗是否显示
        current: '', //当前选择数据行的id
        result: [{
            value: 1,
            label: '处理中'
          },
          {
            value: 2,
            label: '通过'
          },
          {
            value: 3,
            label: '不通过'
          },
          {
            value: 4,
            label: '编辑中'
          },
          {
            value: 5,
            label: '已驳回'
          },
        ], //状态流程状态
        formStatus : [
          {
          value: 0,
          label: ''
        },{
          value: 1,
          label: '变更-'
        },{
          value: 2,
          label: '删除-'
        }],
        processStateList: [
          {
            value: "0-1",
            label: '处理中'
          },
          {
            value: "0-2",
            label: '通过'
          },
          {
            value: "0-3",
            label: '不通过'
          },
          {
            value: "0-4",
            label: '编辑中'
          },
          {
            value: "0-5",
            label: '已驳回'
          },
          {
            value: "1-1",
            label: '变更-处理中'
          },
          {
            value: "1-2",
            label: '变更-通过'
          },
          {
            value: "1-3",
            label: '变更-不通过'
          },
          {
            value: "1-4",
            label: '变更-编辑中'
          },
          {
            value: "1-5",
            label: '变更-已驳回'
          },
        ],
        token: '', //接口请求token
        api: '', //接口请求base_api
        tagIcons: [], //所有字段信息
        rightConfig: {}, //表单发布第三步右侧配置
        panelValues: [], //数据面板数据
        treeData: [], //树数据
        defaultProps: {
          children: "children",
          label: "name"
        }, //树默认属性
        treeKeyword: '', //树节点搜索关键字
        treeNodeValue: null, //树节点值
        showImportDialog: false,
        curTableName: '',
        tableBtn:[],  //头部右侧按钮
        lineBtn:[], //表内按钮
        tagIconsMap: new Map(), // 普通组件tag map
        treeKeyAndLabelMap: new Map(), // 下拉树形value-label的map结构
        tableTagIconsMap: new Map(), // 子表单tag的map
        tableFiledsMap: new Map(), //子表单字段使用
        searchBox:true,
        userList:[], // 搜索用户列表
        searchPageNo:1,
        searchPostPageNo: 1,
        postList:[], // 搜索岗位列表
        deptList:[], // 搜索部门列表
        searchBox:true,
        processDefinitionId:'',
        processInfoId:'',
        spanArr: [],
        leftTreeLoading: true,
        assembleIndexInterval: [], // 存储合并行的 具体 行数
        // 不是子表单的组件列
        notSubformCompIdxList: [],
        isExsitSubform: false, // 是否存在子表单
        subformParams: [], // 存储子表单本身的字段
        timeStamp: Date.now(),
        submitLoading: false,
        bothType: ['el-input','el-number','el-input-number','getMapPoint'], // 单行文本 多行文本 数字  计数器 编码  地点
        timeType: ['time', 'time-range'],
        dateType: ['date', 'date-range'],
        // 只需精准搜索的类型  下拉、级联、单选、多选、树形、行政区域、用户、部门、岗位
        onlyType: ['my-select', 'my-cascader', 'my-radio-group', 'my-checkbox-group', 'el-tree-select', 'my-region', 'UsersSelector', 'DepartmentSelection', 'PostSelection'],
        fieldParamsMap: new Map(), // 存储字段与config对象
        repeatVerifySet: new Set(), // 需要重复校验的字段
        searchTypeMap: new Map(), // 存储字段与查询方式
		    changeobj:{},
        showTemplate: true,//是否显示创建时间、流程状态、序号、复选框
        formConfCopy: {
            fields: []
        },
        tempOp: [],
        otherTableList: [], // 树形列表被过滤掉的数据
        childCurrent:'',
        exportArr: [], // 导出时选中的id数组
        formConfDataView: {  //查看禁用储存数据
          fields: []
        }
      }
    },
    async mounted() {
        this.token = getAccessToken()
        this.api = process.env.VUE_APP_BASE_API
        this.tableLoading = true
        await this.getAllDepart()
        await getUserList([]).then(rsp => {
            if (rsp.code === 0) {
                this.allUserList = [...rsp.data]
            }
        })
        await gePostList([]).then(rsp => {
            if (rsp.code === 0) {
                this.allPostList = [...rsp.data]
            }
        })
        this.getFormDetail() //获取表单详情
        // 浏览器回退事件
        // const _this = this
        // window.addEventListener("popstate", function(e) {
        //     if (_this.showForm) {
        //         _this.showForm = false
        //     }
        // }, false);
    },
    computed: {
      //选择数据条数
      selectionLength() {
        return this.multipleSelection.length
      },
      showStepBtn () {
        this.up = this.formConfData?.fields?.filter((_) => _.__config__.tag === 'Steps')[0]?.__config__.up
        this.down = this.formConfData?.fields?.filter((_) => _.__config__.tag === 'Steps')[0]?.__config__.down
        this.finish = this.formConfData?.fields?.filter((_) => _.__config__.tag === 'Steps')[0]?.__config__.finish
        this.sumbitBtn = this.formConfData?.fields?.filter((_) => _.__config__.tag === 'Steps')[0]?.__config__.sumbitBtn
        const index = this.formConfData?.fields?.findIndex(comp => {
            return comp.__config__.tag === 'Steps'
        })
        if (index !== -1) {
            return true
        }
        return false
      },
      showColFunc () {
        if (this.showApproval) {
            if (this.rightConfig.colConfig.showIndex) {
                if (this.showHideData.length > 0) {
                    return !this.showHideData[this.fieldData.length + 2].hide
                }
            } else {
                return !this.showHideData[this.fieldData.length].hide
            }
        } else {
            return false
        }
      },
      showCreateTime () {
        if (this.showHideData.length>0) {
            if (this.rightConfig.colConfig.showIndex) {
                return !this.showHideData[this.fieldData.length + 1].hide
            } else {
                return !this.showHideData[this.fieldData.length].hide
            }
        }
      }
    },
    watch: {
      // 根据名称筛选部门树
      treeKeyword(val) {
        this.$refs.tree.filter(val);
      },
    //   showForm (newVal, oldVal) {
    //     if (newVal) {
    //         this.pushHistory(true)
    //     } else {
    //         this.pushHistory(false)
    //     }
    //   },
    },
    methods: {
      sumbitSeps() {
      this.$refs.parserRef.submitForm();
    },
      changeSumbit(val) {
        this.showSumbit = val
      },
      // 压入本页路径
      pushHistory (flag) {
          var state = {
              title: document.getElementsByTagName('title')[0].innerText, 
              url: flag ? "#" : location.origin + location.pathname 
          }; 
          window.history.pushState(state, 'title', flag ? "#" : location.origin + location.pathname); 
      },
        getNumber (param) {
            if ((param??'') !== '')  {
                let strParam = String(param)
                let flag = /e/.test(strParam)
                if (!flag) return param
                // 指数符号 true: 正，false: 负
                let sysbol = true
                if (/e-/.test(strParam)) {
                  sysbol = false
                }
                // 指数
                let index = Number(strParam.match(/\d+$/)[0])
                // 基数
                let basis = strParam.match(/^[\d\.]+/)[0].replace(/\./, '')
                if (sysbol) {
                  return basis.padEnd(index + 1, 0)
                } else {
                  return basis.padStart(index + basis.length, 0).replace(/^0/, '0.')
                }
            } else {
                return ''
            }
        },
        resultFmt (scope) {
            return this.formStatus[scope.row.formStatus] ?
                this.formStatus[scope.row.formStatus] && this.formStatus[scope.row.formStatus]?.label + this.result[scope.row.result -1]?.label : this.result[scope.row.result -1]?.label
        },
        formatIndex (index) {
            if (!this.isExsitSubform) {
                return index+(this.page.pageNo-1) * this.page.pageSize + 1
            } else {
                for (let g = 0; g < this.assembleIndexInterval.length; g++) {
                    const numList = this.assembleIndexInterval[g].split('--')
                    if (index >= numList[0] && index <= numList[1]) {
                        return g + (this.page.pageNo - 1) * this.page.pageSize + 1
                    }
                }
            }
        },
      encryptCert(cert){
        return cert?.replace(/^(.{3})(?:\d+)(.{3})$/, "$1*********$2") || ''
      },
      mergeSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (this.isExsitSubform && this.spanArr.length > 0) {
            if (column.type === "selection" || column.label === '序号' || column.label === '创建时间' ||
            this.notSubformCompIdxList.includes(columnIndex) || column.label === '流程状态' || column.label === '操作') {
                const _row = this.spanArr[rowIndex]
                const _col = _row > 0 ? 1 : 0;
                //该形式为行合并
                return{
                    rowspan:_row,
                    colspan:_col
                }
            }
        }
      },
      //批量操作
      handleChange(value) {
        if(value[1] === "删除选中"){
          if (this.multipleSelection.length === 0) {
            this.$message.warning('请至少勾选一条数据')
          }else{
            this.$confirm('确认删除选中数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
              this.multiDel()
            }).catch((e) => {console.log(e)});
          }
          
        }else if (value[1] === "删除全部") {
          this.$confirm('确认删除全部数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                this.multiDelAll()
            }).catch((e) => {
                console.log(e)
          });
        }else if(value[1] === "导出选中"){
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请至少勾选一条数据')
        } else {
            if (this.multipleSelection.length > 1000) {
              this.$confirm('数据量过大导出时间稍长，是否确认导出当前选中？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.tableLoading = true
                this.exportArr = []
                this.multipleSelection.map((item, index) => {
                  this.exportArr.push(item.id)
                })
                const params = {
                  tableName: this.tableName,
                  ids: this.exportArr.join(','),
                  sortField: this.rightConfig.sortConfig.field ? this.rightConfig.sortConfig.field : '',
                  sortType: this.rightConfig.sortConfig.type ? this.rightConfig.sortConfig.type : ''
                }
                getDataOut(params).then(resp => {
                  if (resp && !resp.code) {
                    this.tableLoading = false
                    const url = window.URL.createObjectURL(resp)
                    const link = document.createElement('a')
                    link.href = url
                    link.download = decodeURI(`${this.formName}.xlsx`) // 这里是最后下载下来的excel表格名称
                    document.body.appendChild(link)
                    link.click()
                    window.URL.revokeObjectURL(url)
                    document.body.removeChild(link)
                  }
                }).catch((err) => { console.log(err) })
              }).catch((e) => {
                console.log(e)
              })
            } else {
              this.exportArr = []
              this.multipleSelection.map((item, index) => {
                this.exportArr.push(item.id)
              })
              const params = {
                tableName: this.tableName,
                ids: this.exportArr.join(','),
                sortField: this.rightConfig.sortConfig.field ? this.rightConfig.sortConfig.field : '',
                sortType: this.rightConfig.sortConfig.type ? this.rightConfig.sortConfig.type : ''
              }
              this.tableLoading = true
              getDataOut(params).then(resp => {
                if (!resp.code) {
                  this.tableLoading = false
                  const url = window.URL.createObjectURL(resp)
                  const link = document.createElement('a')
                  link.href = url
                  link.download = decodeURI(`${this.formName}.xlsx`) // 这里是最后下载下来的excel表格名称
                  document.body.appendChild(link)
                  link.click()
                  window.URL.revokeObjectURL(url)
                  document.body.removeChild(link)
                }
              }).catch((err) => { console.log(err) })
            }
          }
        }else if (value[1] === "导出全部") {
          if (this.total > 1000) {
            this.$confirm('数据量过大导出时间稍长，是否确认全部导出？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.tableLoading = true
              const params = {
                tableName: this.tableName,
                sortField: this.rightConfig.sortConfig.field ? this.rightConfig.sortConfig.field : '',
                sortType: this.rightConfig.sortConfig.type ? this.rightConfig.sortConfig.type : ''
              }
              getDataOut(params).then(resp => {
                if (resp && !resp.code) {
                  this.tableLoading = false
                  const url = window.URL.createObjectURL(resp)
                  const link = document.createElement('a')
                  link.href = url
                  link.download = decodeURI(`${this.formName}.xlsx`) // 这里是最后下载下来的excel表格名称
                  document.body.appendChild(link)
                  link.click()
                  window.URL.revokeObjectURL(url)
                  document.body.removeChild(link)
                }
              }).catch((err) => { console.log(err) })
            }).catch((e) => {
              console.log(e)
            })
          } else {
            this.tableLoading = true
            const params = {
              tableName: this.tableName,
              sortField: this.rightConfig.sortConfig.field ? this.rightConfig.sortConfig.field : '',
              sortType: this.rightConfig.sortConfig.type ? this.rightConfig.sortConfig.type : ''
            }
            getDataOut(params).then(resp => {
              if (resp && !resp.code) {
                this.tableLoading = false
                const url = window.URL.createObjectURL(resp)
                const link = document.createElement('a')
                link.href = url
                link.download = decodeURI(`${this.formName}.xlsx`) // 这里是最后下载下来的excel表格名称
                document.body.appendChild(link)
                link.click()
                window.URL.revokeObjectURL(url)
                document.body.removeChild(link)
              }
            }).catch((err) => { console.log(err) })
          }
        } else if(value[1] === "下载选中"){
          if (this.multipleSelection.length === 0) {
            this.$message.warning('请至少勾选一条数据')
          }else{
            this.multiDownload()
          }
        }else if (value[1] === "下载全部") {
          this.multiDownloadAll()
        }else if(value[1] === "发起审批选中"){
          if (this.multipleSelection.length === 0) {
            this.$message.warning('请至少勾选一条数据')
          }else{
             this.$confirm('确认对选中数据发起审批?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
              }).then(() => {
                this.multiApp()
              }).catch((e) => {console.log(e)});
            
          }
        }else if (value[1] === "发起审批全部") {
          // this.$confirm('确认对全部数据发起审批?', '提示', {
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          //   }).then(() => {
          //       this.multiAppAll()
          //   }).catch((e) => {
          //       console.log(e)
          // });
        }
        setTimeout(()=>{
          this.$refs.messageDrop[0].hide()
        },500)
      },
         multiApp() {
        let arr = []
        this.fields && this.fields.map((_) => {
          return arr.push(_.name)
        })
        let dataList = []
        this.multipleSelection  && this.multipleSelection.map((item) => {
          let obj = {}
          arr && arr.map((_) => {
            return obj[_] = item.bpmStore[_]
          })
          let childForm = {
            childTables: item.bpmStore?.childTableStore || []
          }
          let objData ={
            formId: this.formId,
            formRecordId: item.id,
            variables: {...obj,...childForm}
          }
          dataList.push(objData)
        })
        batchCreate(dataList).then((res) => {
          if(res.code === 0){
              this.$message.success('发起审批成功 ')
              this.multipleSelection = [];
              this.$refs.multipleTable.clearSelection();
              this.getTableData()
          }
        })
      },
      multiAppAll() {
      },
      clickBtn(){
        this.valueCascader = []
      },
      getHistoryList () {
        if (this.multipleSelection.length > 1) {
            return this.$message.warning('只能选中一条数据')
        }
        if (this.multipleSelection.length === 0) {
            return this.$message.warning('请勾选一条数据')
        }
        this.processInfoId = this.multipleSelection[0].id;
        this.processDefinitionId = this.multipleSelection[0].processDefinitionId;
        if(!this.processDefinitionId){
                this.$message.error('请先发起审批');
                return;
            }
        this.showHistroyDialog = true
      },
      changePass(row) { //通过 且  关联流程
         this.$confirm("确定要变成此项吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(()=> {
              this.changeobj = row;
              this.changeData(row)
          })
      },
      changeData(row) {
        this.status = 'change'
        this.title = '变更'
        this.current = row.id
        const tempObj = {}
        tempObj.tableNames = []
        // 存储所有子表单的字段name
        const fieldNameList = []
        if (this.rightConfig.panelType === 'tree-list') {
            this.treeTableOptions = []
            this.treeTableOptions = deepClone(this.tableData)
            this.makeTreeList(this.treeTableOptions)
        }
        this.formConfData.fields.forEach(cur => {
            if (this.rightConfig.panelType === 'tree-list' && cur.__vModel__ === this.rightConfig.treeConfig.parentParams) {
                cur.options = [...this.treeTableOptions]
            }
            if (['UsersSelector', 'DepartmentSelection', 'PostSelection'].includes(cur.__config__.tag)) {
                cur.pageFlag = 'edit'   //变更功能：变更与编辑逻辑一致，change改为edit，直接回显的是初始设置的预设值
            }
            if (cur.__config__.tag === 'Subform') {
                tempObj.tableNames.push(cur.__vModel__)
                cur.__config__.children[0].__config__.children.forEach(child => {
                    fieldNameList.push(child.__vModel__)
                })
            }
        })
        const tableValueMap = new Map()
        // 是否存在子表单
        if (tempObj.tableNames.length > 0) {
            tempObj.id = row.data_id
            tempObj.versionId = row.version_id
            // 调用接口去查询相关子表单的数据
            getChildListData(tempObj).then(resp => {
                if (resp.code === 0) {
                    // 子表单塞值
                    resp.data.forEach(obj => {
                        obj.data.forEach(item => {
                            const keys = Object.keys(item)
                            for (let a = keys.length - 1; a >= 0 ; a--) {
                                const ele = keys[a]
                                if (!fieldNameList.includes(ele)) {
                                    delete item[ele]
                                }
                                if (fieldNameList.includes(ele)) {
                                    // 根据存储值换相应值(第二个参数'format'，暂时无法获取，format代替，问题未处理)
                                    item[ele] = this.setFormatValue(item[ele], 'format', this.tableTagIconsMap.get(ele)?.tag, this.tableTagIconsMap.get(ele)?.option,this.tableTagIconsMap.get(ele)?.dataType)
                                }
                            }
                            item.showComp = true
                        })
                        tableValueMap.set(obj.tableName, obj.data)
                    })
                    this.formConfData.fields.forEach(cur => {
                        if (cur.__config__.tag === 'Subform') {
                            cur.tableData = tableValueMap.get(cur.__vModel__)
                        }
                    })
                    // 主表赋值
                    this.fields.map((item,index)=>{
                      let  value = row[item.name]
                      let option = this.tagIconsMap.get(item.name)?.option
                      if(this.tagIconsMap.get(item.name)?.tag === 'coding'){
                        value = row.bpmStore[item.name]
                        option=[{
                          label: row[item.name],
                          value: row.bpmStore[item.name]
                        }]
                        this.codeReshow = {
                          label: row[item.name],
                          value: row.bpmStore[item.name]
                        }
                      }
                      this.originData[item.name] = this.setFormatValue(value, item.format, this.tagIconsMap.get(item.name)?.tag, option,this.tagIconsMap.get(item.name).dataType)
                    })
                    const stepsList = this.formConfData.fields.filter((_) => _.__config__.tag === 'Steps')
                    if(stepsList?.length > 0){  //步骤条预览都是从步骤一开始
                      this.formConfData.fields.filter((_) => _.__config__.tag === 'Steps')[0].__config__.active = 1
                    }
                    this.showSumbit = false
                    this.showForm = true
                    this.dialogVisible = true
                }
            })
        } else {
            // 不存在子表单时
            this.fields.map((item,index)=>{
              let  value = row[item.name]
              let option = this.tagIconsMap.get(item.name).option
              if(this.tagIconsMap.get(item.name)?.tag === 'coding'){
                value = row.bpmStore[item.name]
                option=[{
                  label: row[item.name],
                  value: row.bpmStore[item.name]
                }]
                this.codeReshow = {
                  label: row[item.name],
                  value: row.bpmStore[item.name]
                }
              }
              this.originData[item.name] = this.setFormatValue(value, item.format, this.tagIconsMap.get(item.name)?.tag, option,this.tagIconsMap.get(item.name).dataType)
            })
            const stepsList = this.formConfData.fields.filter((_) => _.__config__.tag === 'Steps')
            if(stepsList?.length > 0){  //步骤条预览都是从步骤一开始
              this.formConfData.fields.filter((_) => _.__config__.tag === 'Steps')[0].__config__.active = 1
            }
            this.showSumbit = false
            this.showForm = true
            this.dialogVisible = true
        }
      },
      delpass(row) {
         this.$confirm('确认删除选中数据?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(() => {
             let arr = []
              this.fields && this.fields.map((_) => {
                return arr.push(_.name)
              })
              let obj = {}
              arr && arr.map((_) => {
                return obj[_] = row[_]
              })
              createProcessInstance({
                  formId: this.formId,
                  formRecordId: row.id,
                  variables: obj,
                  formStatus: 2 //删除
                }).then(res => {
                    this.$message.success('变更成功 ')
                    this.dialogVisible = false
                    this.showForm = false
                    this.tableLoading = true
                    this.page.pageNo = 1
                    this.$refs.multipleTable.clearSelection()
                    this.getTableData()
                })
          })
      },
      //初始化数据
      initData(data) {
        //isSelect状态：true为选中状态，false为未选中状态 ，空字符串为未知状态
        //适配树形，则要递归
        this.loopIsSelected(data)
        // data.forEach((item)=>{
        //   if(item.children?.length >0){
        //     item.children.forEach(i =>{
        //       i.isSelect = false
        //     })
        //   }
        //   item.isSelect = false
        // })
      },
      loopIsSelected (list) {
        list.forEach((item) => {
            if (item.children?.length >0) {
              this.loopIsSelected(item.children)
            }
            item.isSelect = false;
        });
      },
      //复选框点击事件
      selectFun(selection, row) {
        this.setRowIsSelect(row);
        this.groupArray = []
        if(this.rightConfig.panelType === 'tree-list') {
          this.loopSelectFun(selection)
          this.groupArray = [...new Set(this.groupArray)]
        }else{
          selection.forEach((item,index)=>{
            if(item.isSelect){
              if(!item.children){
                this.groupArray.push(item) 
              }else{
                item.children.forEach((i,index)=>{
                  this.groupArray.push(i)
                })
              }
            }
          })
          this.groupArray = [...new Set(this.groupArray)]
        }
      },
      loopSelectFun(list){
        list.forEach((item,index)=>{
          if(item.isSelect){
            this.groupArray.push(item)
            if(item.children){
              this.loopSelectFun(item.children)
            }
          }
        })
      },
      
      setRowIsSelect(row) {
        //当点击父级点复选框时，当前的状态可能为未知状态，所以当前行状态设为false并选中，即可实现子级点全选效果
        if (!row.isSelect) {
            row.isSelect = false;
            this.$refs.multipleTable.toggleRowSelection(row, true);
        }
        row.isSelect = !row.isSelect;
        //判断操作的是子级点复选框还是父级点复选框，如果是父级点，则控制子级点的全选和不全选
        if (row.children && row.children.length > 0) {
            // 存在树结构，需要用到递归
            this.loopToggleRowSelect(row.children, row.isSelect)
        } else {
            //操作的是子节点  1、获取父节点  2、判断子节点选中个数，如果全部选中则父节点设为选中状态，如果都不选中，则为不选中状态，如果部分选择，则设为不明确状态
            let parentId = row.parentId;
            this.tableData.forEach((item) => {
                let isAllSelect = [];
                if (parentId && item.id && item.id == parentId)  {
                    item.children.forEach((childrenItem) => {
                        isAllSelect.push(childrenItem.isSelect);
                    });
                    if (isAllSelect.every((selectItem) => {
                        return true == selectItem;
                    })) {
                        item.isSelect = true;
                        this.$refs.multipleTable.toggleRowSelection(item, true);
                    } else if (isAllSelect.every((selectItem) => {
                        return false == selectItem;
                    })) {
                        item.isSelect = false;
                        this.$refs.multipleTable.toggleRowSelection(item, false);
                    } else {
                        item.isSelect = "";
                        // this.$refs.multipleTable.toggleRowSelection(item, false);
                    }
                }
            });
        }
      },
      loopToggleRowSelect (list, flag) {
        list.forEach((item) => {
            item.isSelect = flag;
            this.$refs.multipleTable.toggleRowSelection(item, flag);
            if (item.children) {
                this.loopToggleRowSelect(item.children, flag)
            }
        });
      },
      //检测表格数据是否全选
      checkIsAllSelect() {
        this.oneProductIsSelect = [];
        this.tableData.forEach((item) => {
          this.oneProductIsSelect.push(item.isSelect);
        });
        //判断一级产品是否是全选.如果一级产品全为true，则设置为取消全选，否则全选
        let isAllSelect = this.oneProductIsSelect.every((selectStatusItem) => {
          return true == selectStatusItem;
        });
        return isAllSelect;
      },

      //表格全选事件
      selectAllFun(selection) {
        // 树形列表全选事件优化
        if (this.rightConfig.panelType === 'tree-list') {
            this.isAllTreeSelect = !this.isAllTreeSelect
            this.splite(this.tableData, this.isAllTreeSelect);
        } else {
            let isAllSelect = this.checkIsAllSelect();
            this.tableData.forEach((item) => {
              item.isSelect = isAllSelect;
              this.$refs.multipleTable.toggleRowSelection(item, !isAllSelect);
              this.selectFun(selection, item);
            });
        }
      },
      /* 处理数据*/
      splite(data, flag) {
        data.forEach((row) => {
            this.$refs.multipleTable.toggleRowSelection(row, flag); // districtTable  el-table里绑定的ref
            if (row.children != undefined) {
                this.splite(row.children, flag);  // parentDetailWithRelationshipVOS   子节点的数据
            }
        });
      },
      // 表格行样式 当当前行的状态为不明确状态时，添加样式，使其复选框为不明确状态样式
      rowClassNameFun({ row }) {
        if (row.isSelect === "") {
          return "indeterminate";
        }
      },

      // 表格标题样式 当一级目录有为不明确状态时，添加样式，使其全选复选框为不明确状态样式
      headerRowClassName({ row }) {
        let oneProductIsSelect = [];
        this.tableData?.forEach((item) => {
          oneProductIsSelect.push(item.isSelect);
        });
        if (oneProductIsSelect.includes("")) {
          return "indeterminate";
        }
        return "";
      },
        jumpStepBtn (flag) {
            this.$refs.parserRef.jumpBtnStep(flag);
        },
        async getAllDepart () {
            await geDeptList([]).then(res => {
                this.departAllList = [...res.data] || []
                // list.forEach(cur => {
                //     this.departMap.set(cur.id + '', cur.name)
                // })
            })
        },
        // 获取部门信息以便展示
        getNameById (value) {
            // const idLst = value?.split(',') || []
            // let rowStr = ''
            // idLst.forEach(item => {
            //     rowStr += this.departMap.get(item) + ','
            // })
            // return rowStr
            return value
        },
        closeTableDialog (obj) {
            this.showImportDialog = false
            if (obj.flag) {
                this.getTableData()
            }
        },
        importData () {
            this.showImportDialog = true
        },
        drawerClick(renderKey){
            const idx = this.getIRagIndex(renderKey);
            const childrenList=this.formConfData.fields[idx].__config__.children[0].__config__.children
            const showNum=this.formConfData.fields[idx].__config__.showNum
            showNum ? this.showHideData.push({columnName:'序号', hide: false}):[]
            childrenList.forEach(item=>{
                this.showHideData.push({
                    renderKey: renderKey,
                    columnName: item.__config__.label,
                    hide: false
                })
            })
            this.drawer=true
        },
        closeForm () {
            this.showSumbit = false
            this.formConfData = JSON.parse(JSON.stringify(this.formConfDataView))  //查看 disabled都是true，拿之前的数据
            this.showForm = false;
            this.formConfData.fields.forEach(comp => {
                if (comp.__config__.tag === "Subform") {
                    comp.tableData = []
                }
            });
        },
      //富文本重置
      reset() {
        this.showSumbit = false
        this.time = new Date().getMilliseconds()
      },
      //表单关联流程
      getProcessInData() {
        getProcessIn(this.formId).then((res) => {
          this.showApproval = res.data
        })
      },
      //根据id获取表单详情
       getFormDetail() {
        let path = this.$route.path.split('/')
        const _this = this
        getFormInfo(path[path.length - 1]).then((res) => {
          const data=res
          if (res.code === 0) {
            setTimeout(()=> {
              res.data?.manageMenuId && getBtnInfo(res.data?.manageMenuId).then(res=>{
              this.tableBtn=[]
              this.lineBtn=[]
              _this.rightConfig.btnConfig?.filter((btn)=>{return btn.position==='inline'}).map((item)=>{
               let btnPermision= res.data.filter((btns)=>{
                  return btns.name===item.label
                })
                if(btnPermision.length>0){
                  _this.lineBtn.push(item)
                }
              })
              // _this.lineBtn = _this.lineBtn.filter((_) => _.label != "发起审批")
              if(_this.lineBtn.length > 2){
                this.lineBtnList = this.lineBtn.slice(0,2)
                this.dropList = this.lineBtn.slice(2,this.lineBtn.length)
              }
              _this.rightConfig.btnConfig?.filter((btn)=>{return btn.position==='table'}).map((item)=>{
               let btnPermision= res.data.filter((btns)=>{
                  return btns.name===item.label
                })
                if(btnPermision.length>0){
                  this.tableBtn.push(item)
                }
              })
              let num= 0
              let arrData = []//按钮label
              let arrBtn  //是否关联流程
              if(this.showApproval){
                arrBtn = ['批量删除','导出','附件下载','批量发起审批']
              }else{
                arrBtn = ['批量删除','导出','附件下载']
              }
              let tempArray= []  //批量操作中的按钮
              let tempDel = [{
                label:'删除选中',
                value:'删除选中'
                },{
                  label:'删除全部',
                  value:'删除全部'
              }]
              let tempExport = [{
                label:'导出选中',
                value:'导出选中'
                },{
                  label:'导出全部',
                  value:'导出全部'
              }]
              let tempDownload = [{
                label:'下载选中',
                value:'下载选中'
                },{
                  label:'下载全部',
                  value:'下载全部'
              }]
              let multiApproval = [{
                label:'发起审批选中',
                value:'发起审批选中'
              }]
              this.tableBtn.map((item,index)=>{
                arrData.push(item.label)
                if(item.label === '批量删除'){
                  tempArray.push({
                    label:'删除',
                    value:'删除',
                    children:tempDel
                  })

                }else if(item.label === '导出'){
                  tempArray.push({
                    label:'导出',
                    value:'导出',
                    children:tempExport
                  })
                }else if(item.label === '附件下载'){
                  tempArray.push({
                    label:'附件下载',
                    value:'附件下载',
                    children:tempDownload
                  })
                }else if(item.label === '批量发起审批'){
                   tempArray.push({
                    label:'批量发起审批',
                    value:'批量发起审批',
                    children:multiApproval
                  })
                }
              })
              this.optionsCascader = tempArray
              arrData.map((item,index)=>{
                if(arrBtn.indexOf(item) !==-1){
                  num++
                }
              })
              if(num>0){
                this.tableBtn.push({
                  label:'批量操作',
                  method:'piliang',
                  position:'table',
                  text:'批量操作',
                  type:'default'
                })
              }
              this.tableBtn = this.tableBtn.filter((item)=>{
                return arrBtn.indexOf(item.label) ===-1
              })
              // this.rightConfig.btnConfig.filter((btn)=>{return btn.position==='inline'})
              //部署最新代码后显示
              // this.parseData(data)
            })
            },500)
              this.parseData(data) //解析数据，渲染页面
              this.time = new Date().getMilliseconds()
          }
        }).catch(e => console.log(e))
      },
      //获取最新的面板数据和左侧树数据
      updateOptions() {
        if (this.rightConfig.panelType === 'data' || this.rightConfig.panelType === 'left-data') {
          this.refreshPanelValue()
        }
        if (this.rightConfig.panelType === 'left' || this.rightConfig.panelType === 'left-data') {
          // !this.treeData.length && this.refreshTreeNodes()
          this.refreshTreeNodes()
        }
      },
      loopSetTagObj (tree) {
        tree.forEach(newComp => {
            if (newComp.value) {
                newComp.tag = this.tagIconsMap.get(newComp.value)?.tag,
                newComp.dataType = this.tagIconsMap.get(newComp.value)?.dataType,
                newComp.options = this.tagIconsMap.get(newComp.value)?.option
            }
            newComp.children && this.loopSetTagObj(newComp.children)
        })
      },
      //解析json
      async parseData(res) {
        this.formId = res.data.id
        this.tableName = res.data.tableName
        this.formName = res.data.formName
        this.outerChain = res.data.outerChain
        this.formPath = window.location.protocol+"//"+window.location.host+res.data.path
        this.formConfData = JSON.parse(res.data.formJsonUser)
        await this.getTagIcons(this.formConfData.fields)
        this.setFieldMap(this.formConfData.fields)
        const subformIdxLst = []
        this.onlySubformParams = []
        this.formConfData.fields.forEach((compTemp, index) => {
            if (compTemp.__config__.tag === 'Subform') {
                // 存储子表单的下标
                subformIdxLst.push(index)
                this.isExsitSubform = true
                // 存储子表单的字段
                this.onlySubformParams.push(compTemp.__vModel__)
            }
        })
        this.formConfData.formName = res.data.formName
        this.formJsonMessage = JSON.parse(res.data.formJsonMessage)
        this.rightConfig = this.formJsonMessage.rightConfig
        this.fields = JSON.parse(res.data.formJsonData).data
        const tableHeadFieldLst = []
        if (res.data.childFormJsonData) {
            const tempList = JSON.parse(res.data.childFormJsonData)
            tempList.forEach(test => {
                const jsonData = JSON.parse(test.formJsonData)
                jsonData.forEach(jay => {
                    this.tableFiledsMap.set(test.tableName + '-' + jay.name, jay)
                })
                // 组装子表单的多表头数据
                const jsonLink = JSON.parse(test.formJsonUser)
                const listObj = {}
                listObj.name = jsonLink.__config__.label
                listObj.value = jsonLink.__vModel__
                const childFieldLst = []
                jsonData.forEach(temp => {
                    const obj = this.formJsonMessage.alignConfig.find((item) => {
                        return item.columnName === temp.name
                    })
                    if (obj) {
                      childFieldLst.push({
                          name: temp.desc,
                          value: temp.name,
                          format: temp.format,
                          sorting: temp.sorting ? temp.sorting : false,
                          align: temp.align ? temp.align : 'center',
                          width: temp.width ? temp.width : '200',
                          tag: this.tableTagIconsMap.get(temp.name)?.tag,
                          dataType: this.tableTagIconsMap.get(temp.name)?.dataType,
                          options: this.tableTagIconsMap.get(temp.name)?.option
                      })
                    }
                })
                listObj.children = [...childFieldLst]
                childFieldLst.length > 0 && tableHeadFieldLst.push(listObj)
            })
        }
        //通过权限控制按钮显示
        // const nameBtnList=this.btnConfig.map(item=>item.name)
        // this.buttonPermissions=this.formJsonMessage.rightConfig?.btnConfig?.filter(item=>nameBtnList.includes(item.label))
        //排序配置
        this.fieldName = this.rightConfig.sortConfig.field
        this.order = this.rightConfig.sortConfig.type
        this.oldfieldName = this.rightConfig.sortConfig.field
        this.oldorder = this.rightConfig.sortConfig.type
        //分页配置
        this.pagination = this.rightConfig.paginationConfig.isPag
        this.page.pageSize = Number(this.rightConfig.paginationConfig.pageSize.replace('条', ''))
        //弹窗配置
        // this.dialogTop = this.formJsonMessage.basic.high || '20%'
        // this.dialogWidth = this.formJsonMessage.basic.frame || '50%'
        this.dialogTop = `${this.formConfData.dialogTop}px` || '20%'
        this.dialogWidth = `${this.formConfData.dialogWidth}px`|| '50%'
        let columns = []
        // 是否启用了多表头配置
        if (this.rightConfig?.tableHeaderConfig?.multistage) {
            this.loopSetTagObj(this.rightConfig.tableHeaderConfig.treeHeaderData)
            this.fieldData = [...this.rightConfig.tableHeaderConfig.treeHeaderData]
        } else {
            //表单发布列配置，只显示配置的列，且按配置顺序显示列
             const curList = this.formJsonMessage.alignConfig.filter((item) => {
              return item.columnName
            })
            const _this = this
            curList.forEach((item)=>{
                let index = this.fields.findIndex((data)=>{
                    return data.name === item.columnName
                })
                if (index > -1) {
                    columns.push({
                        columnName: this.fields[index].desc,
                        hide: false
                    })
                    this.fieldData.push({
                        name: _this.fields[index].desc,
                        value: _this.fields[index].name,
                        format: _this.fields[index].format,
                        sorting: item.sorting ? item.sorting : false,
                        align: item.align ? item.align : 'center',
                        width: item.width ? item.width : '200',
                        tag: _this.tagIconsMap.get(item.columnName)?.tag,
                        dataType: _this.tagIconsMap.get(item.columnName)?.dataType,
                        options: _this.tagIconsMap.get(item.columnName)?.option
                    })
                } else {
                }
              })
              await getProcessIn(this.formId).then((res) => {
                this.showApproval = res.data
                if(res.data){
                    if (this.rightConfig.colConfig.showIndex) {
                        this.showHideData = [
                            {
                                columnName: '序号',
                                hide: false
                            },
                                ...columns, 
                            {
                                columnName: '创建时间',
                                hide: false
                            },
                            {
                                columnName: '流程状态',
                                hide: false
                            }
                        ]
                    } else {
                        this.showHideData = [
                                ...columns,
                            {
                                columnName: '创建时间',
                                hide: false
                            },
                            {
                                columnName: '流程状态',
                                hide: false
                            }
                        ]
                    }
                } else {
                    if (this.rightConfig.colConfig.showIndex) {
                        this.showHideData = [
                            {
                                columnName: '序号',
                                hide: false
                            }, ...columns, {
                                columnName: '创建时间',
                                hide: false
                            }
                        ]
                    } else {
                        this.showHideData = [
                            ...columns,
                            {
                                columnName: '创建时间',
                                hide: false
                            }
                        ]
                    }
                }
            })
        }
        // 插入子表单的表头
        subformIdxLst.forEach((cur, idx) => {
            if (tableHeadFieldLst.length - 1 >= idx) {
                this.fieldData.splice(cur, 0, tableHeadFieldLst[idx])
                if (this.rightConfig.colConfig.showIndex) {
                    this.showHideData.splice(this.fieldData.length, 0, {
                        columnName: tableHeadFieldLst[idx].name,
                        hide: false
                    })
                }
            }
        })
        //表单发布搜索配置
        const nextList = this.formJsonMessage.searchConfig.filter((item,index) => {
            if (item.checked) {
                let curType = ''
                if (!item.searchType) {
                    const config = this.fieldParamsMap.get(item.field)
                    if (config) {
                        if (this.bothType.includes(config.tag)) {
                            item.searchType = 'like'
                        } else if (this.onlyType.includes(config.tag) || this.timeType.includes(config.tagIcon)) {
                            item.searchType = 'equals'
                        } else if (this.dateType.includes(config.tagIcon)) {
                            item.searchType = 'between'
                        }
                    } else {
                        item.searchType = ''
                    }
                }else if(this.formConfData.fields[index]?.['value-format'] === 'yyyy'){
                  item.searchType = 'equals'
                }
                this.searchTypeMap.set(item.field,item.searchType)
            }
            return item.checked
        })
        let typedata,dictname,searchTag,fieldName,tableName,fields;
      
        nextList.forEach((item) => {
          for(let info of this.formConfData.fields){
              if(info.__vModel__===item.field){
                typedata = info.dataType;
                dictname = info.dictName;
                searchTag = info.__config__.tag;
                fieldName = info.fieldName;
                tableName = info.tableName;
                fields = info.fields;
                break;
              }
              if (info.__config__.tag === 'Subform' && info.__config__.children[0].__config__.children.length > 0) {
                for(let curComp of info.__config__.children[0].__config__.children){
                    if(curComp.__vModel__ === item.field){
                        typedata = curComp.dataType;
                        dictname = curComp.dictName;
                        searchTag = curComp.__config__.tag;
                        fieldName = curComp.fieldName;
                        tableName = curComp.tableName;
                        fields = curComp.fields;
                        break;
                    }
                }
              }
          }
          if (item.category === 'data') {
            let index = this.fields.findIndex((data)=>{
              return data.name === item.field
            })
            if (index > -1) {
                this.searchData.push({
                    name: this.fields[index].desc,
                    value: item.field,
                    type: item.category,
                    format: this.fields[index]?.format,
                    tag: this.tagIconsMap.get(item.field)?.tag,
                    options: this.tagIconsMap.get(item.field)?.option,
                    dataType:typedata,
                    dictName:dictname,
                    searchTag,
                    fieldName,
                    tableName,
                    fields,
                    searchType: this.formConfData.fields[index]?.['value-format'] === 'yyyy' ? 'equals' : item.searchType, //类型为年的时候 只能等于查询
                    valueFormat :this.formConfData.fields[index]?.['value-format'],
                    dataPickerType: this.formConfData.fields[index]?.type
                })
            } else {
                this.searchData.push({
                    name: this.tableTagIconsMap.get(item.field)?.label,
                    value: this.tableTagIconsMap.get(item.field)?.params,
                    type: item.category,
                    tag: this.tableTagIconsMap.get(item.field)?.tag,
                    options: this.tableTagIconsMap.get(item.field)?.option,
                    dataType:typedata,
                    dictName:dictname,
                    searchTag,
                    fieldName,
                    tableName,
                    fields,
                    searchType: this.formConfData.fields[index]?.['value-format'] === 'yyyy' ? 'equals' : item.searchType, //类型为年的时候 只能等于查询
                    valueFormat :this.formConfData.fields[index]?.['value-format'],
                    dataPickerType: this.formConfData.fields[index]?.type
                })
            }
          } else {
            return {
              value: item.field,
              type: item.category,
            }
          }
        })
       this.handleOnload();
        this.tableShow = true
        this.getTableData()
        this.getProcessInData()
      },

      //获取具有全字段的数据，为了导出做数据准备
      funcTemp(records){
        const copyList = deepClone(records)
        let newList = []
        let ExportAllData = []
        copyList.forEach((item) => {
            item.childTables && item.childTables.forEach((child) => {
                item[child.tableName] = child.data
            })
            newList.push(item)
        })
        this.notSubformCompIdxList = []
        this.subformParams = []
        // 此数字跟列表的 序号 列有关，如果存在 序号 列，则 字段列 从2开始，如果不存在序号列，则从1开始
        let calcCount = this.rightConfig.colConfig.showIndex ? 2 : 1
        // 使用过滤后的字段来计算列数
        this.fieldData.forEach((compTemp) => {
            if (this.isExsitSubform) {
                if (compTemp.children) {
                    // 子表单的字段
                    this.subformParams.push(compTemp.value)
                    calcCount = calcCount + compTemp.children.length
                } else {
                    // 存储不是子表单的列
                    this.notSubformCompIdxList.push(calcCount++)
                }
            }
        })
        // 如果存在子表单的列，再处理合并
        if (this.isExsitSubform) {
            // 组装好的管理列表数据
            const assembleTableList = []
            this.assembleIndexInterval = []
            newList?.forEach((data, rowIndex) => {
                data.mergeId = data.id;
                // 查出行里每个子表单的行数，然后求出最大值
                const numList = this.subformParams.map(insideSubform => {
                    if (data[insideSubform]) {
                        return JSON.parse(data[insideSubform]).length
                    } else {
                        return 0
                    }
                })
                // 计算出子表单数据最多的行数
                let maxLength = Math.max.apply(null, numList)
                // 存在多个子表单数据量不一样多
                if (maxLength > 0) {
                    for (let a = 0;a < maxLength; a++) {
                        // 每次开始新长度的对象，应该重新开始赋值
                        let tempObj = {
                            ...data,
                        }
                        this.subformParams.forEach(insideSubform => {
                            if (data[insideSubform]) {
                                // 某一个子表单的数据
                                const subformDataList = JSON.parse(data[insideSubform])
                                if (subformDataList[a]) {
                                    delete subformDataList[a].version_id
                                    delete subformDataList[a].data_id
                                    delete subformDataList[a].id
                                    tempObj = {
                                        ...tempObj,
                                        ...subformDataList[a]
                                    }
                                }
                            }
                        })
                        assembleTableList.push(tempObj)
                    }
                } else {
                    // 存在子表单没有填数据
                    maxLength = 1
                    assembleTableList.push({ ...data })
                }
                let lastLineNum = 0
                if (rowIndex > 0) {
                    lastLineNum = parseInt(this.assembleIndexInterval[rowIndex - 1].split('--')[1])
                }
                if (this.assembleIndexInterval.length > 0) {
                    this.assembleIndexInterval.push((lastLineNum + 1) + '--' + (lastLineNum + maxLength))
                } else {
                    this.assembleIndexInterval.push('0--' + (rowIndex + lastLineNum + maxLength - 1))
                }
            })
            // 合并表格行以渲染
            this.transformRow(assembleTableList)
            ExportAllData = [...assembleTableList]
            return ExportAllData
            // this.$nextTick(() => {
            //     console.clear()
            // })
        } else {
            // 不存在子表单，直接赋值
            ExportAllData = newList
            return ExportAllData
        }
      },
      handleOnload(){
         // 先替换表单字段里的数据(js加载事件)
         if(this.formConfData?.formJs?.onLoad){
            this.formConfCopy.fields = [...this.formConfData.fields]
            bindEventScript.call(this, '', '', this.formConfData.formJs.onLoad);
        }
        let numChange = 0
        let numBlur = 0
        // this.formConfData.fields.forEach((item,index)=>{
        //   if(item.__config__.children){
        //     item.__config__.children[0].__config__.children.forEach((child,index)=>{
        //       if(child.change){
        //         console.log(child)
        //         this.formConfCopy.fields = [...this.formConfData.fields]
        //         bindEventScript.call(this, '', '', child.change);
        //         numChange++
        //       }
        //       if(child.blur){
        //         this.formConfCopy.fields = [...this.formConfData.fields]
        //         bindEventScript.call(this, '', '', child.blur);
        //         numBlur++
        //       }
        //     })
        //   }else{
        //     if(item.change){
        //       this.formConfCopy.fields = [...this.formConfData.fields]
        //       bindEventScript.call(this, '', '', item.change);
        //       numChange++
        //     }
        //     if(item.blur){
        //       this.formConfCopy.fields = [...this.formConfData.fields]
        //       bindEventScript.call(this, '', '', item.blur);
        //       numBlur++
        //     }
        //   }
        // })
        const _this = this
          setTimeout(() => {
            if(this.formConfData?.formJs?.onLoad){
                let tempMap = new Map()
                for (const showItem of _this.fieldData) {
                    let count = 1
                    // 替换表头里的options选项值，以便展示相对应的label
                    if (showItem.children?.length > 0) {
                        // 子表单的处理
                        for (const tableItem of showItem.children) {
                            _this.tempOp = []
                            _this.loopGetOptions(tableItem.value, _this.formConfCopy.fields)
                            if (_this.tempOp.length > 0) {
                                tableItem.options = [..._this.tempOp]
                            }
                            tempMap.set(tableItem.value, tableItem.options)
                        }
                        count++
                    }
                    if (count === showItem.children?.length) {
                        continue
                    }
                    _this.tempOp = []
                    _this.loopGetOptions(showItem.value, _this.formConfCopy.fields)
                    if (_this.tempOp.length > 0) {
                        showItem.options = [..._this.tempOp]
                    }
                    tempMap.set(showItem.value, showItem.options)
                }
                // 查询条件里的下拉框值
                for (const searchItem of _this.searchData) {
                    const list = tempMap.get(searchItem.value)
                    if (list?.length) {
                        searchItem.options = [...list]
                    }
                }
            }
        }, 2000);
      },
      loopGetOptions (prop, list) {
            if (this.tempOp?.length > 0) {
                return
            }
            list.forEach(item => {
                if (['el-card', 'el-tabs', 'Steps', 'el-collapse'].includes(item.__config__.tag)) {
                    item.__config__.children.forEach(comp => {
                        return this.loopGetOptions(prop, comp.__config__.children)
                    })
                } else if ('Subform' === item.__config__.tag) {
                    item.__config__.children[0].__config__.children.forEach(comp => {
                        if (prop === comp.__vModel__ && Array.isArray(comp.options)) {
                            this.tempOp = [...comp.options]
                            return
                        }
                    })
                } else {
                    if (prop === item.__vModel__ && Array.isArray(item.options)) {
                        this.tempOp = [...item.options]
                        return
                    }
                }
            })
      },
      // 组装字段与属性的map
      setFieldMap (list) {
        list.forEach(curComp => {
            if (['Steps', 'el-card','el-tabs','Steps', 'el-collapse', 'Subform'].includes(curComp.__config__.tag)) {
                //布局组件，遍历内部子组件
                const newList = curComp.__config__.children
                for (const item of newList) {
                    this.setFieldMap(item.__config__.children)
                }
            } else {
                // 存储需要重复校验的字段
                if (curComp.__config__.repeatVerify) {
                    this.repeatVerifySet.add(curComp.__vModel__)
                }
                this.fieldParamsMap.set(curComp.__vModel__, curComp.__config__)
            }
        })
      },
      //获取表数据
      getTableData() {
        let searchData = {
          ...this.searchFormData,

        }
        let searchParamsData = {};
        let searchTypeObj = {}
        //左侧树查询
        if (this.rightConfig.panelType === 'left' || this.rightConfig.panelType === 'left-data') {
          if(this.rightConfig.leftConfig.field && this.treeNodeValue !== null) {
            if (this.treeNodeValue !== '') {
              if (typeof this.treeNodeValue === Array) {  //部门数据或带子级数据源
                if (searchData[this.rightConfig.leftConfig.field]) {
                 searchData[this.rightConfig.leftConfig.field] = [...this.treeNodeId,`'${searchData[this.rightConfig.leftConfig.field]}'`]
                } else {
                 searchData[this.rightConfig.leftConfig.field] = this.treeNodeId
                }
              } else {
                searchData[this.rightConfig.leftConfig.field] = this.treeNodeId
              }
            }
          }
        }
        for (let key in searchData) {
            let config = this.searchData.filter((item) => {
                return item.value === key
            })
            if(searchData[key]===undefined || searchData[key]===null){
                searchData[key]='';
            }
            searchData[key] = this.getFormatValue(searchData[key], config[0].tag, config[0].format) //搜索值处理
            if(searchData[key]!==undefined && searchData[key]!==null && searchData[key]!==''){
                if(config[0].tag!=='slider' && config[0].tag!=='rate'){
                searchParamsData[key] = searchData[key];
                }else if(config[0].tag==='slider' && searchData[key]!==0){
                searchParamsData[key] = searchData[key];
                }else if(config[0].tag==='rate' && searchData[key]!==0){
                searchParamsData[key] = searchData[key];
                }
            }
            searchTypeObj[key] = this.searchTypeMap.get(key)
        }
        if (this.rightConfig.panelType === 'tree-list') {
            const flag = this.formConfData.fields.some(comp => {
                return comp.__config__.tag === 'el-tree-select'
            })
            getListData({
                tableName: this.tableName,
                seachData: searchData,
                searchType: searchTypeObj,
                dataType: 'all',
                isPage: false,
                formStatusAndResult: this.processStatus
            }).then(async (res) => {
               res.data.records.map((item) => {
                  item.childTables && item.childTables.map((child) => {
                    item[child.tableName] =  child.data
                  })
                })
                // 查全部数据以备查上级的label
                const newRes = await getListData({
                    formStatusAndResult: '',
                    tableName: this.tableName,
                    dataType: 'all',
                    isPage: false,
                })
                // maketreelist使用(全部数据)
                this.tableDataOriginal = deepClone(newRes.data.records)
                this.tableData = deepClone(res.data.records)
                this.initData(this.tableData)
                if (flag && this.rightConfig.treeConfig.childrenParams && this.rightConfig.treeConfig.parentParams) {
                    this.tableData = this.handleTreeFmt(res.data.records, 'data_id', this.rightConfig.treeConfig.parentParams) || []
                    //注
                    this.otherTableList = [...res.data.records]
                    // 获取被过滤掉的数据
                    this.cancatList(this.tableData)
                    // 重新合并
                    this.tableData = this.tableData.concat(this.otherTableList)
                    // 处理脏数据(没有父级数据，但有子级)
                    if (res.data.records?.length > 0 && this.tableData.length === 0) {
                        this.tableData = [...res.data.records]
                    }
                    this.initData(this.tableData)
                }
                // 此处处理是为了搜索条件不会重新初始化
                if (this.treeTableOptions.length === 0 && this.tableData.length > 0) {
                    this.treeTableOptions = deepClone(this.tableData) || []
                    this.makeTreeList(this.treeTableOptions)
                    this.searchData.forEach(curItem => {
                        if (curItem.value === this.rightConfig.treeConfig.parentParams) {
                            curItem.options = [...this.treeTableOptions]
                        }
                    })
                    this.searchData = [...this.searchData]
                }
                this.tableLoading = false
            })
        } else {
            //查询参数
            let params = {
                tableName: this.tableName,
                searchType: searchTypeObj,
                seachData: searchParamsData,
                startDate: this.datetime ? this.datetime[0] : '',
                endDate: this.datetime ? this.datetime[1] : '',
                fieldName: this.fieldName,
                order: this.order,
                dataType: '2',
                groupField:this.rightConfig.panelType==='grouping'?this.rightConfig.groupField:'',
                formStatusAndResult: this.processStatus,
                isPage: this.pagination   //true 有分页 false没有分页
            } 
            if (this.pagination) { //分页
              params.current = this.page.pageNo
              params.size = this.page.pageSize
            }
            const _that = this
            _that.tableData = []
            //获取符合条件列表数据
            getListData(params).then((res) => {
                if (res.code === 0) {
                  let newList = []
                    if (Array.isArray(res.data.records) && res.data.records?.length > 0) {
                        const copyList = deepClone(res.data.records)
                        copyList.forEach((item) => {
                            item.childTables && item.childTables.forEach((child) => {
                                item[child.tableName] = child.data
                            })
                            newList.push(item)
                        })
                        this.notSubformCompIdxList = []
                        this.subformParams = []
                        // 此数字跟列表的 序号 列有关，如果存在 序号 列，则 字段列 从2开始，如果不存在序号列，则从1开始
                        let calcCount = this.rightConfig.colConfig.showIndex ? 2 : 1
                        // 使用过滤后的字段来计算列数
                        this.fieldData.forEach((compTemp) => {
                            if (this.isExsitSubform) {
                                if (compTemp.children) {
                                    // 子表单的字段
                                    this.subformParams.push(compTemp.value)
                                    calcCount = calcCount + compTemp.children.length
                                } else {
                                    // 存储不是子表单的列
                                    this.notSubformCompIdxList.push(calcCount++)
                                }
                            }
                        })
                        // 如果存在子表单的列，再处理合并
                        if (this.isExsitSubform) {
                            // 组装好的管理列表数据
                            const assembleTableList = []
                            this.assembleIndexInterval = []
                            newList?.forEach((data, rowIndex) => {
                                data.mergeId = data.id;
                                // 查出行里每个子表单的行数，然后求出最大值
                                const numList = this.subformParams.map(insideSubform => {
                                    if (data[insideSubform]) {
                                        return JSON.parse(data[insideSubform]).length
                                    } else {
                                        return 0
                                    }
                                })
                                // 计算出子表单数据最多的行数
                                let maxLength = Math.max.apply(null, numList)
                                // 存在多个子表单数据量不一样多
                                if (maxLength > 0) {
                                    for (let a = 0;a < maxLength; a++) {
                                        // 每次开始新长度的对象，应该重新开始赋值
                                        let tempObj = {
                                            ...data,
                                        }
                                        this.subformParams.forEach(insideSubform => {
                                            if (data[insideSubform]) {
                                                // 某一个子表单的数据
                                                const subformDataList = JSON.parse(data[insideSubform])
                                                if (subformDataList[a]) {
                                                    delete subformDataList[a].version_id
                                                    delete subformDataList[a].data_id
                                                    delete subformDataList[a].id
                                                    tempObj = {
                                                        ...tempObj,
                                                        ...subformDataList[a]
                                                    }
                                                }
                                            }
                                        })
                                        assembleTableList.push(tempObj)
                                    }
                                } else {
                                    // 存在子表单没有填数据
                                    maxLength = 1
                                    assembleTableList.push({ ...data })
                                }
                                let lastLineNum = 0
                                if (rowIndex > 0) {
                                    lastLineNum = parseInt(this.assembleIndexInterval[rowIndex - 1].split('--')[1])
                                }
                                if (this.assembleIndexInterval.length > 0) {
                                    this.assembleIndexInterval.push((lastLineNum + 1) + '--' + (lastLineNum + maxLength))
                                } else {
                                    this.assembleIndexInterval.push('0--' + (rowIndex + lastLineNum + maxLength - 1))
                                }
                            })
                            // 合并表格行以渲染
                            this.transformRow(assembleTableList)
                            this.tableData = [...assembleTableList]
                            // this.$nextTick(() => {
                            //     console.clear()
                            // })
                        } else {
                            // 不存在子表单，直接赋值
                            this.tableData = newList
                        }
                    } else {
                        this.tableData = newList
                    }
                    if(this.rightConfig.panelType === 'grouping'){
                        this.fieldData = this.fieldData.filter(cur => {
                            return cur.value !== this.rightConfig.groupField
                        })
                        this.tableData.forEach((item,index)=>{
                            item[this.fieldData[0].value] = item.groupField
                        })
                    }
                    this.total = res.data.total
                    this.tableLoading = false
                    this.updateOptions() //更新面板和左侧树
                }
            }).catch(e => {
              console.log(e)
              this.tableLoading = false
            })
        }
      },
	  cancatList (tableData) {
        tableData.forEach(item => {
            this.otherTableList = this.otherTableList.filter(cur => {
                return cur.id !== item.id
            })
            item.children && this.cancatList(item.children, this.otherTableList)
        })
      },
      // 重新合并表格行以渲染并导出
      transformRow (tableList) {
        this.spanArr = []
        let contactDot = 0;
        tableList.forEach((item,index) => {
            //遍历tableData数据，给spanArr存入一个1，第二个item.mergeId和前一个item.mergeId是否相同，相同就存
            //spanArr前一位加1，spanArr再存入0，因为spanArr为n的项表示n项合并，为0的项表示该项不显示
            if(index === 0){
                this.spanArr.push(1)
            } else {
                if (item.mergeId === tableList[index - 1].mergeId) {
                    this.spanArr[contactDot] += 1;
                    this.spanArr.push(0);
                } else {
                    contactDot = index;
                    this.spanArr.push(1);
                }
            }
        })
      },
      handleTreeFmt(data, id, parentId) {
        id = id || 'id'
        parentId = parentId || 'parentId'
        //对源数据深度克隆
        const cloneData = JSON.parse(JSON.stringify(data))
        //循环所有项
        const treeData = cloneData.filter(father => {
            let branchArr = cloneData.filter(child => {
                //返回每一项的子级数组
                return father[id] + '' == child[parentId] + ''
            });
            branchArr.length > 0 ? father.children = branchArr : '';
            //返回第一层
            return father[parentId]  === '' || father[parentId]  === undefined ||father[parentId]  === 0;
        });
        return treeData !== '' ? treeData : data;
      },
      //获取面板计算值
      async refreshPanelValue() {
        this.panelValues = []
        for(let i=0;i<this.rightConfig.panelConfig.length;i++){
          let item = this.rightConfig.panelConfig[i]
          if (item.field && this.tableData.length > 0) {
            let str = this.fields.find(t=>{
              return t.name===item.field;
            }).format;
            if(str.indexOf('int')>-1){
              let params = {
              columnName: item.field,
              formula: item.method,
              tableName: this.tableName
              }
              let res = await getFormulaValue(params)
              if (res.code === 0) {
                this.panelValues.push(res.data.data)
              }
            }else{
              let params = {
              fieldName: item.field,
              fun: item.method.toUpperCase(),
              tableName: this.tableName
            }
              let res = await getComputeFieldNew(params);
              if(res.code === 0){
                let n = res.data.total || res.data.sun;
                this.panelValues.push(n)
              }
            }
          } else {
            this.panelValues.push('')
          }
        }
      },
      // 生成左侧树结构
      async refreshTreeNodes() {
        let type = this.rightConfig.leftConfig.datasource
        let nodes = []
        if (type === 'datasource') {  //数据源
          if (this.rightConfig.leftConfig.showField && this.rightConfig.leftConfig.table) {
            let res = await sourceTestList(this.rightConfig.leftConfig.table)
            // let child = await getAllListData({tableName: this.rightConfig.leftConfig.table})
            let children = []
            res.data?.rowMaps.map((item) => {
              let node = {
                name: item[this.rightConfig.leftConfig.showField]
              }
              // if (this.rightConfig.leftConfig.childField) {
              //   let childNodes = child.data.filter((c) => {
              //   return c[this.rightConfig.leftConfig.showField] === item
              // }).map((n) => {
              //   return {name:n[this.rightConfig.leftConfig.childField]}
              // })
              //   if (childNodes.length > 0) {
              //     let obj = {};
              //     let objarr = childNodes.reduce((pre,val)=>{
              //       if(!obj[val.name]){
              //         pre.push(val);
              //         obj[val.name] = true;
              //       }
              //       return pre;
              //     },[]);
              //     node.children = objarr
              //   }
              // }
              children.push(node)
            })
            nodes.push({
              name: this.rightConfig.leftConfig.showFieldName,
              children: children
            })
          }
        } else if (type === 'dict') {  //字典
          if (this.rightConfig.leftConfig.dict) {
            let child = await getDictData({
              dictType: this.rightConfig.leftConfig.dict
            })
            let children = []
            child.data.map((item) => {
              children.push({
                name: item.label
              })
            })
            nodes.push({
              name: this.rightConfig.leftConfig.dictName,
              children: children
            })
          }
        } else {  //部门数据
          let child = await listSimpleDepts()
          nodes.push(...this.handleTree(child.data, "id"));
        }
        this.treeData = nodes
        this.leftTreeLoading = false
      },
      handleTreeType(n,type){
         let fieldinfo = this.fieldData.find(val=>{
              return val.value === this.rightConfig.leftConfig[type];
            });
            if(fieldinfo.tag==='select'){
             let str = '';
             if(fieldinfo.options && Array.isArray(fieldinfo.options)){
              str = fieldinfo.options.find(val=>{
                return val.value==n;
              })
              str = str && str.label || '';
            }
            return str;
            }else{
              return n
            }
      },
       // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data,node) {
        // 适配点击左侧树名称查询当前节点的管理列表数据
        if (data.id) {
            this.treeNodeId = data.id
        } else {
            this.treeNodeId = data.name
        }
        if (node.level === 1) {
          this.treeNodeValue = ''
        } else {
          if (this.rightConfig.leftConfig.datasource === 'depart' || (this.rightConfig.leftConfig.datasource === 'datasource' && this.rightConfig.leftConfig.childField)) {  //部门数据
            if (node.isLeaf) {  //叶子节点
              this.treeNodeValue = data.name
            } else {  //父节点
              let dept = ["'!#%@$^'",`'${data.name}'`]
              this.getAllNodes(dept,node.childNodes)
              this.treeNodeValue = dept
            }
          } else {
            this.treeNodeValue = data.name
          }
        }
        this.tableLoading = true
        this.getTableData()
      },
      //生成所有节点
      getAllNodes(dept,childNodes) {
        childNodes.map((item) => {
          if (item.childNodes.length > 0) {
            this.getAllNodes(dept,item.childNodes)
          }
          dept.push(`'${item.data.name}'`)
        })
      },
      //按钮点击事件
      operateData(row,position,label) {
         if (label === '编辑') {
            this.changeobj = row
            this.editData(row,position)
         } else if (label === '删除') {
            this.$confirm('确认删除此表单?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delData(row,position)
            }).catch((e) => {
                console.log(e)
            });
         } else if (label === '查看') {
            this.viewData(row,position)
         } else if (label === '复制') {
            this.copyData(row,position)
         } else if (label === '导出') {
            this.exportToExcel(row,position)
            // this.exportData()
         }
      },
      //插入数据
      insertData() {
        this.time = Date.now()
        this.status = 'add'
        this.title = '新增'
        this.originData = {}
        if (this.rightConfig.panelType === 'tree-list') {
            this.treeTableOptions = []
            this.treeTableOptions = deepClone(this.tableData)
            this.makeTreeList(this.treeTableOptions)
        }
        this.formConfData.fields.forEach(cur => {
            if (this.rightConfig.panelType === 'tree-list' && cur.__vModel__ === this.rightConfig.treeConfig.parentParams) {
                cur.options = [...this.treeTableOptions]
            }
            if (['UsersSelector', 'DepartmentSelection', 'PostSelection'].includes(cur.__config__.tag)) {
                cur.pageFlag = 'create'
            }
        })
        this.formConfDataView = JSON.parse(JSON.stringify(this.formConfData))
        const stepsList = this.formConfData.fields.filter((_) => _.__config__.tag === 'Steps')
        if(stepsList?.length > 0){  //步骤条预览都是从步骤一开始
          this.formConfData.fields.filter((_) => _.__config__.tag === 'Steps')[0].__config__.active = 1
        }
        this.showSumbit = false
        this.dialogVisible = true
        this.showForm = true
      },
      //撤回
      withdrawData(row) {
        const id = row.processInstanceId;
        this.$prompt('请输入撤回原因？', "撤回流程", {
          type: 'warning',
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /^(?!\s*$)(?!.*<|>|;|'|javascript|jscript|vbscript).+$/i, // 判断非空，且非空格，且不能包含特殊字符
          inputErrorMessage: "撤回原因不能为空，且不能含有特殊字符",
        }).then(({
          value
        }) => {
          return cancelProcessInstance(id, value);
        }).then(() => {
          this.$modal.msgSuccess("撤回成功");
          this.tableLoading = true
          this.multipleSelection = [];
          this.$refs.multipleTable.clearSelection();
          this.getTableData()
        })
      },
      //修改数据
      editData(row,position) {
        if(position === 'table') {
          row = this.multipleSelection[0]
        }
        this.status = 'edit'
        this.title = '编辑'
        // this.originData = {}
        this.current = row.id
        this.childCurrent = row.data_id
        this.viewAndEditSameFunc(row, 'edit')
      },
      // 处理层级关系
      makeTreeList (children) {
            for (let a = 0; a < children.length; a++) {
                const obj = children[a]
                const keys = Object.keys(obj)
                let str = obj['data_id'];
                keys.forEach(key => {
                    if (this.rightConfig.treeConfig.childrenParams === key) {
                        obj.label = obj[key]
                        obj.value = str;
                    }
                    if (key !== 'children') {
                        delete obj[key]
                    }
                })
                obj.children?.length > 0 && this.makeTreeList(obj.children)
            }
        },
      //复制数据
      copyData(row,position) {
        if(position === 'table') {
          row = this.multipleSelection[0]
        }
        let fields = []
        const tableValueList = []
        this.fields.map((item, index) => {
          if (row[item.name] !== undefined && row[item.name] !== null) {
            fields.push({
              name: item.name,
              type: item.format,
              value: row[item.name]
            })
          }
        })
        
        row.childTableStore && row.childTableStore.map((i) => {
          i.data.forEach(params => {
                  const obj = {}
                  obj.data = []
                  delete params.approve_status
                  delete params.create_time
                  delete params.creator
                  delete params.id
                  delete params.parent_id
                  delete params.tenant_id
                  delete params.update_time
                  delete params.version_id
                  // delete params.data_id
                  const keyLst = Object.keys(params)
                   keyLst.forEach(insideKey => {
                      const tempObj= {}
                      if(insideKey !== "data_id"){
                        tempObj.type = this.tableFiledsMap.get(i.tableName + '-' + insideKey)?.format
                        tempObj.name = insideKey
                        tempObj.value = this.getFormatValue(params[insideKey], this.tableTagIconsMap.get(insideKey)?.tag, tempObj.type)
                        obj.data.push(tempObj)
                      }
                    })
                  obj.tableName = i.tableName
                  obj.dataId = row.id
                  tableValueList.push(obj)
                })
        })
        let dataAll = {
            sysFromInsertDataVo: {
              tableName: this.tableName,
              dataType: '2',
              repeatVerifyList: Array.from(this.repeatVerifySet),
              data: fields
            },
            sysFromInsertDataVoList: tableValueList
        }



       

        insertdataall(dataAll).then((res) => {
          if (res.code === 0) {
            this.$message.success('复制成功')
            this.dialogVisible = false
            this.showForm = false
            this.tableLoading = true
            this.page.pageNo = 1
            this.$refs.multipleTable.clearSelection()
            this.getTableData()
          }
        }).catch(e => console.log(e))
      },
      //查看数据
      viewData(row,position) {
        if (position === 'table') {
          row = this.multipleSelection[0]
        }
        if (row.processInstanceId && row.result != 4) {
            let obj = {}
            if (this.rightConfig.panelType === 'tree-list') {
                obj =  {
                    panelType: this.rightConfig.panelType,
                    childrenParams: this.rightConfig.treeConfig.childrenParams,
                    parentParams: this.rightConfig.treeConfig.parentParams,
                    tableName: this.tableName
                }
            }
            this.$router.push({
                path: getProcessDetailPath(),
                query: {
                    id: row.processInstanceId,
                    details: 'details',
                    ...obj,
                    tableId: row.id,
                    result: row.result,
                    toView: 'toView',
                    path:this.$route.path
                },
            });
             window.sessionStorage.setItem('childList',JSON.stringify(row))
        } else {
            this.status = 'view'
            this.title = '查看'
            this.viewAndEditSameFunc(row, 'view')
        }
      },
      // 查看和编辑具有 相同的 代码逻辑
      viewAndEditSameFunc (row, flag) {
            const tempObj = {}
            tempObj.tableNames = []
            this.formConfDataView = JSON.parse(JSON.stringify(this.formConfData))
            // 存储所有子表单的字段name
            const fieldNameList = []
            if (this.rightConfig.panelType === 'tree-list') {
                this.treeTableOptions = []
                this.treeTableOptions = deepClone(this.tableData)
                this.makeTreeList(this.treeTableOptions)
            }
            this.formConfData.fields.forEach(cur => {
                if (this.rightConfig.panelType === 'tree-list' && cur.__vModel__ === this.rightConfig.treeConfig.parentParams) {
                    cur.options = [...this.treeTableOptions]
                }
                if (['UsersSelector', 'DepartmentSelection', 'PostSelection'].includes(cur.__config__.tag)) {
                    cur.pageFlag = 'edit'
                }
                if (cur.__config__.tag === 'Subform') {
                  tempObj.tableNames.push(cur.__vModel__)
                  cur.__config__.children[0].__config__.children.forEach(child => {
                    fieldNameList.push(child.__vModel__)
                    if(this.status === 'view'){
                      child.disabled = true
                    }
                  })
                }else{
                  if(this.status === 'view'){
                    cur.disabled = true
                  }
                }
            })
            const tableValueMap = new Map()
            // 是否存在子表单
            if (tempObj.tableNames.length > 0) {
                tempObj.id = row.data_id
                tempObj.versionId = row.version_id
                // 调用接口去查询相关子表单的数据
                getChildListData(tempObj).then(resp => {
                    if (resp.code === 0) {
                        // 子表单塞值
                        resp.data.forEach(obj => {
                            obj.data.forEach(item => {
                                const keys = Object.keys(item)
                                for (let a = keys.length - 1; a >= 0 ; a--) {
                                    const ele = keys[a]
                                    if (!fieldNameList.includes(ele)) {
                                        delete item[ele]
                                    }
                                    if (fieldNameList.includes(ele)) {
                                        // 根据存储值换相应值(第二个参数'format'，暂时无法获取，format代替，问题未处理)
                                        item[ele] = this.setFormatValue(item[ele], 'format', this.tableTagIconsMap.get(ele)?.tag, this.tableTagIconsMap.get(ele)?.option,this.tableTagIconsMap.get(ele)?.dataType)
                                    }
                                }
                                item.showComp = true
                            })
                            tableValueMap.set(obj.tableName, obj.data)
                        })
                        this.formConfData.fields.forEach(cur => {
                            if (cur.__config__.tag === 'Subform') {
                                cur.tableData = tableValueMap.get(cur.__vModel__)
                            }
                        })
                        // 主表赋值
                        this.fields.map((item,index)=>{
                          let  value = row[item.name]
                          let option = this.tagIconsMap.get(item.name)?.option
                          if(this.tagIconsMap.get(item.name)?.tag === 'coding'){
                            value = row.bpmStore[item.name]
                            option=[{
                              label: row[item.name],
                              value: row.bpmStore[item.name]
                            }]
                            this.codeReshow = {
                              label: row[item.name],
                              value: row.bpmStore[item.name]
                            }
                          }
                          this.originData[item.name] = this.setFormatValue(value, item.format, this.tagIconsMap.get(item.name)?.tag, option,this.tagIconsMap.get(item.name).dataType)
                        })
                        const stepsList = this.formConfData.fields.filter((_) => _.__config__.tag === 'Steps')
                        if(stepsList?.length > 0){  //步骤条预览都是从步骤一开始
                          this.formConfData.fields.filter((_) => _.__config__.tag === 'Steps')[0].__config__.active = 1
                        }
                        this.showSumbit = false
                        this.showForm = true
                        this.dialogVisible = true
                    }
                })
            } else {
                // 不存在子表单时
                // this.fields.map((item,index)=>{
                //     this.originData[item.name] = this.setFormatValue(row[item.name], item.format, this.tagIconsMap.get(item.name).tag, this.tagIconsMap.get(item.name).option,this.tagIconsMap.get(item.name).dataType)
                // })
                this.fields.map((item,index)=>{
                  let  value = row[item.name]
                  let option = this.tagIconsMap.get(item.name).option
                  if(this.tagIconsMap.get(item.name)?.tag === 'coding'){
                    value = row.bpmStore[item.name]
                    option=[{
                      label: row[item.name],
                      value: row.bpmStore[item.name]
                    }]
                    this.codeReshow = {
                      label: row[item.name],
                      value: row.bpmStore[item.name]
                    }
                  }
                  this.originData[item.name] = this.setFormatValue(value, item.format, this.tagIconsMap.get(item.name)?.tag, option,this.tagIconsMap.get(item.name).dataType)
                })
                let arr = this.searchData.filter(info=>{
                    return info.searchTag==='my-region'
                });
                for(let infoval of arr){
                    this.originData[infoval.value] = row[infoval.value].split(',');
                }
                const stepsList = this.formConfData.fields.filter((_) => _.__config__.tag === 'Steps')
                if(stepsList?.length > 0){  //步骤条预览都是从步骤一开始
                  this.formConfData.fields.filter((_) => _.__config__.tag === 'Steps')[0].__config__.active = 1
                }
                this.showSumbit = false
                this.showForm = true
                this.dialogVisible = true
            }
      },
      //发起审批
      approvalData(row,position) {
        if (position === 'table') {
          row = this.multipleSelection[0]
        }
        let arr = []
        this.fields && this.fields.map((_) => {
          return arr.push(_.name)
        })
        let obj = {}
        arr && arr.map((_) => {
          return obj[_] = row.bpmStore[_]
        })
        let childForm = {
          childTables: row.bpmStore?.childTableStore || []
        }
        // if(row.childTables.length > 0) {  //有子表单
        //      row.childTables.map((item) => {
        //         childForm[item.tableName] =  item.data
        //     })
        // } 
        if(row.bpmStore.approve_status == 0){
            createProcessInstance({
            formId: this.formId,
            formRecordId: row.id,
            variables: {...obj,...childForm}
          }).then(res => {
            if(res.code === 0){
              this.$message.success('发起审批成功 ')
              this.tableLoading = true
              this.multipleSelection = [];
              this.$refs.multipleTable.clearSelection();
              this.getTableData()
            }
          })
        }else{
           let fieldNew = [], tableValueList = []
          let createObjNew = {}
          const _this = this
          this.fields.map((item, index) => {
            if (row[item.name] !== undefined && row[item.name] !== null) {
              let value = this.getFormatValue(row.bpmStore?row.bpmStore[item.name]:row[item.name], _this.tagIconsMap.get(item.name).tag, item.format) //格式化数据，转化为数据库存储类型
                  fieldNew.push({
                      name: item.name,
                      type: item.format,
                      value: value
                  })
                  createObjNew[item.name] = value
            }
          })
            fieldNew.push({
              name: 'version_id',
              type: 'TINYINT',
              value: row?.version_id + 1,
            })
            fieldNew.push({
              name: 'data_id',
              type: 'BIGINT',
              value: row?.data_id+'',
            })
            row.childTableStore?.map((i) => {
                i.data.forEach(params => {
                  const obj = {}
                  obj.data = []
                  delete params.approve_status
                  delete params.create_time
                  delete params.creator
                  delete params.id
                  delete params.parent_id
                  delete params.tenant_id
                  delete params.update_time
                  delete params.version_id
                  // delete params.data_id
                  const keyLst = Object.keys(params)
                   keyLst.forEach(insideKey => {
                      const tempObj= {}
                      if(insideKey !== "data_id"){
                        tempObj.type = this.tableFiledsMap.get(i.tableName + '-' + insideKey)?.format
                        tempObj.name = insideKey
                        tempObj.value = this.getFormatValue(params[insideKey], this.tableTagIconsMap.get(insideKey)?.tag, tempObj.type)
                        obj.data.push(tempObj)
                      }
                    })
                    obj.data.push({
                      name: 'version_id',
                      type: 'TINYINT',
                      value: row?.version_id + 1,
                    })
                  obj.data.push({
                    name: 'data_id',
                    type: 'BIGINT',
                    value: params?.data_id+'',
                  })
                  obj.tableName = i.tableName
                  obj.dataId = row.id
                  tableValueList.push(obj)
                })
                 
            })
            const dataInsert = {
                  sysFromInsertDataVo: {
                    tableName: this.tableName,
                    dataType: '2',
                    repeatVerifyList: Array.from(this.repeatVerifySet),
                    data: fieldNew,
                },
               sysFromInsertDataVoList: tableValueList  //子表单的数据
              } 
              insertdataall(dataInsert).then((res) => {
                if(res.code === 0){
                   createProcessInstance({
                    formId: this.formId,
                    formRecordId:res.data?res.data:'',
                    variables: {...obj,...childForm}
                  }).then(res => {
                    if(res.code === 0){
                      this.$message.success('发起审批成功 ')
                      this.tableLoading = true
                      this.multipleSelection = [];
                      this.$refs.multipleTable.clearSelection();
                      this.getTableData()
                    }
                  })
                }
              })
        }
        
      },
      //删除数据
      delData(row,position) {
        if (position === 'table') {
          row = this.multipleSelection[0]
        }
        let ids = []
        ids.push(row.id)
        let processInstanceIds = [] //实例id
        processInstanceIds.push(row.processInstanceId)
        deletedata({
          tableName: this.tableName,
          ids: ids.join(',')
        }).then((res) => {
          if (res.code === 0) {
            // 关联流程后 需要删除实列 processInstanceId 为null 不调删除实列的接口
            if (this.showApproval) { //关联实列
              deleteExampleData({
                instanceIds: processInstanceIds
              }).then((res) => {
                this.$message.success('删除成功')
                this.tableLoading = true
                // 返回到原记录所在页面，而当原记录所在页不存在时，则返回上一页
                if (this.page.pageNo > 1 && (this.total - 1) <= (this.page.pageNo - 1) * this.page.pageSize) {
                  this.page.pageNo--
                }
                this.$refs.multipleTable.clearSelection()
                this.getTableData()
              })
            } else { // 没关联实例
              this.$message.success('删除成功')
              this.tableLoading = true
              // 返回到原记录所在页面，而当原记录所在页不存在时，则返回上一页
              if (this.page.pageNo > 1 && (this.total - 1) <= (this.page.pageNo - 1) * this.page.pageSize) {
                this.page.pageNo--
              }
              this.$refs.multipleTable.clearSelection()
              this.getTableData()
            }
          }
        })
      },

      //删除操作
      handleCommand(command){
        if(command ==='multiDel'){
          this.$confirm('确认删除选中数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.multiDel()
            }).catch((e) => {
                console.log(e)
          });
        }else{
          this.$confirm('确认删除全部数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.multiDelAll()
            }).catch((e) => {
                console.log(e)
          });
        }
      },
      //批量删除数据
      multiDel() {
        let ids =[]
        if(this.rightConfig.panelType === 'grouping'){
          this.groupArray.map((item) => {
            ids.push(item.id)
          })
        }else{
          ids = this.multipleSelection.map((item) => {
            return item.id
          })
        }
        deletedata({
          tableName: this.tableName,
          ids: ids.join(',')
        }).then((res) => {
          if (res.code === 0) {
            this.$message.success('删除成功')
            this.multipleSelection = []
            this.tableLoading = true
            this.page.pageNo = 1
            this.$refs.multipleTable.clearSelection()
            this.getTableData()
          }
        })
      },
      //全部删除
      multiDelAll(){
        deletedataAll({tableName: this.tableName}).then((res) => {
          if (res.code === 0) {
            this.$message.success('删除成功')
            this.multipleSelection = []
            this.tableLoading = true
            this.page.pageNo = 1
            this.$refs.multipleTable.clearSelection()
            this.getTableData()
          }
        })
      },
      //批量导出
      multiExport() {
        let ids =[]
        if(this.rightConfig.panelType === 'grouping'||this.rightConfig.panelType === 'tree-list'){
          this.groupArray.map((item) => {
            ids.push(item.id)
          })
          ids = [...new Set(ids)]
        }else{
          ids = this.multipleSelection.map((item) => {
            return item.id
          })
        }
        //获取选中数据
        getIdsData({
          tableName: this.tableName,
          ids: ids.join(',')
        }).then((res) => {
          if (res.code === 0) {
            this.$message.success('批量导出成功')
            let exceldata = res.data.map((item, serial) => {
              let data = {}
              this.fields.map((key, index) => {
                let value = item[key.name]
                let tag = this.tagIconsMap.get(key.name)?.tag
                if (this.specialTypes.includes(tag)) {
                  value = this.getShowValue(value, tag, this.tagIconsMap.get(key.name).dataType, this.tagIconsMap.get(key.name).option)
                } else if (tag=== 'datetime') {
                  value = this.getDateTime(value)
                } else if (tag === 'upload') {
                  value = this.getFile(value)
                } else if (tag === 'email') {
                  value = [value]
                } else if (tag === 'rich-text') {
                  value = this.getTinymce(value)
                }
                data[key.name] = value?value:' '
              })
              return data
            })
            let column = []
            this.fields.map((item,index)=>{
              let temp = {}
              let tag = this.tagIconsMap.get(item.name)?.tag
              temp['title'] = item.desc
              temp['key'] = item.name
              if(tag === 'upload' && this.isImage || tag === 'email'){
                temp['type'] = 'image'
                temp['width']= 300,
                temp['height']= 300
              }else{
                temp['type'] = 'text'
              }
              column.push(temp)
            })
            const excelName = `${this.formName}`
            table2excel(column,exceldata,excelName)
          }
        }).catch(e => console.log(e))
      },

      //全部导出
      multiExportAll(){
        getAllListData({
            tableName: this.tableName
          }).then((res) => {
            if (res.code === 0) {
              this.$message.success('全部导出成功')
              let exceldata = res.data.map((item, serial) => {
                let data = {}
                this.fields.map((key, index) => {
                  let value = item[key.name]
                  let tag = this.tagIconsMap.get(key.name)?.tag
                  if (this.specialTypes.includes(tag)) {
                    value = this.getShowValue(value, tag, this.tagIconsMap.get(key.name).dataType, this.tagIconsMap.get(key.name).option)
                  } else if (tag=== 'datetime') {
                    value = this.getDateTime(value)
                  } else if (tag === 'upload') {
                    value = this.getFile(value)
                  } else if (tag === 'email') {
                    value = [value]
                  } else if (tag === 'rich-text') {
                    value = this.getTinymce(value)
                  }
                  data[key.name] = value?value:' '
                })
                return data
              })
              let column = []
              this.fields.map((item,index)=>{
                let temp = {}
                let tag = this.tagIconsMap.get(item.name)?.tag
                temp['title'] = item.desc
                temp['key'] = item.name
                if(tag === 'upload' && this.isImage || tag === 'email'){
                  temp['type'] = 'image'
                  temp['width']= 300,
                  temp['height']= 300
                }else{
                  temp['type'] = 'text'
                }
                column.push(temp)
              })
              const excelName = `${this.formName}`
              table2excel(column,exceldata,excelName)
            }
          }).catch(e => console.log(e))
      },

      //判断backFields是否为空
      funcTrue(backFields){
        let bool = true;
        backFields.map((item)=>{
          if(JSON.parse(item).length > 0){
            bool = false
          }
        })
        return bool
      },
      //批量附件下载
      multiDownload(){
        let uploadField = []
        this.backFields = []
        this.fields.map((key, index) => {
          let tag = this.tagIconsMap.get(key.name)?.tag
          if(tag === 'upload'){
            uploadField.push(key.name)
          }
        })
        this.groupArray.map((item,index)=>{
          for( let key in item){
            if(uploadField.indexOf(key) !==-1){
              this.backFields.push(item[key])
              // let arrayUplaod =  JSON.parse(item[key])
              // arrayUplaod.map((i,index)=>{
              //     this.backFields.push(i.url)
              // })
            }
          }
        })
        if(!this.funcTrue(this.backFields)){
          let params = {
          vesList: this.backFields.join(';')
          }
          getVesDataPoc(params).then((response) => {
            this.$download.zip(response, 'POC_' + (parseInt(Math.random() * 10000))  + '.zip');
          }).catch(e => {console.log(e)})
        }else{
          this.$message.warning("无可下载附件");
        }
      },
      
      //全部附件下载
      multiDownloadAll(){
        let uploadField = []
        this.fields.map((key, index) => {
          let tag = this.tagIconsMap.get(key.name)?.tag
          if(tag === 'upload'){
            uploadField.push(key.name)
          }
        })
        let params = {
          tableName:this.tableName,
          fieldNameList:uploadField.join(';')
        }
        //判断是否有附件
        isNullFile(params).then((res) => {
          if(res.data){
            getVesDataPocAll(params).then((response) => {
              this.$download.zip(response, 'POC_' + (parseInt(Math.random() * 10000))  + '.zip');
            }).catch(e => {console.log(e)})
          }else{
            this.$message.warning('无可下载附件')
          }
        }).catch(e => {console.log(e)})
      },

      //导入数据
      uploadSuccess(response, file, fileList) {
        if (response.code === 0) {
          this.$message.success(response.msg)
        } else if (response.code === 500) {
          this.$message.warning(response.msg)
        }
        this.page.pageNo = 1
        this.tableLoading = true
        this.getTableData()
      },
      //上传失败执行
      uploadError(err, file, fileList) {
        this.$message.error(`导入失败${err}`)
      },
      //上传前执行
      beforeUpload(file) {
        console.log(file)
      },
      // 多表头合并行导出方法
      exportData(list, pageNo, pageSize,fieldDataCopy){
        let excelName = `${this.formName}.xlsx`;
        var xlsxParam = { raw: true };//转换成excel时，使用原始的格式
        this.tableLoading = true
        // 克隆节点
        this.hiddenOperating = true
        setTimeout(() => {
            let tables = document.getElementById("out-table").cloneNode(true);
            // 判断是否为固定列，解决（为固定列时，会重复生成表格）
            if (tables.querySelector('.el-table__fixed') !== null) {
                tables.removeChild(tables.querySelector('.el-table__fixed'))
            }
            let table_book = XLSX.utils.table_to_book(tables,xlsxParam);
            var table_write = XLSX.write(table_book, {
                bookType: "xlsx",
                bookSST: true,
                type: "array"
            });
            try {
                FileSaver.saveAs(
                    new Blob([table_write], { type: "application/octet-stream" }),
                    excelName
                );
                this.transformRow(list);
                // this.tableShow = false
                this.fieldData = fieldDataCopy
                this.tableData = [...list]
                this.showTemplate = true
                // 如果导出之前不是第一页，需要重新赋值page信息
                if (pageNo) {
                    this.page.pageNo = pageNo;
                }
                if (pageSize) {
                    this.page.pageSize = pageSize;
                }
                // this.$refs['multipleTable'].toggleAllSelection()
                this.tableShow = true
                this.tableLoading = false
                this.hiddenOperating = false
            } catch (e) {
                this.tableShow = true
                if (typeof console !== "undefined") console.log(e, table_write);
                this.tableData = [...list]
                this.hiddenOperating = false
                this.tableLoading = false
            }
            return table_write;
        },2000)
      },
      //导出excel
      exportToExcel(row,position) {
        if (position === 'inline') {
          let exceldata = []
          let data = {}
          this.fields.map((key, index) => {
            let value = row[key.name]
            let tag = this.tagIconsMap.get(key.name)?.tag
            if (this.specialTypes.includes(tag)) {
              value = this.getShowValue(value, tag, this.tagIconsMap.get(key.name).dataType, this.tagIconsMap.get(key.name).option)
            } else if (tag === 'datetime') {
              value = this.getDateTime(value)
            } else if (tag === 'upload') {
              value = this.getFile(value)
            } else if (tag === 'email') {
              value = [value]
            } else if (tag === 'rich-text') {
              value = this.getTinymce(value)
            }
            data[key.name] = value
          })
          exceldata.push(data)
          let column = []
          this.fields.map((item,index)=>{
            let temp = {}
            let tag = this.tagIconsMap.get(item.name)?.tag
            temp['title'] = item.desc
            temp['key'] = item.name
            if(tag === 'upload' && this.isImage  || tag === 'email'){
              temp['type'] = 'image'
              temp['width']= 300,
              temp['height']= 300
            }else{
              temp['type'] = 'text'
            }
            column.push(temp)
          })
          const excelName = `${this.formName}`
          table2excel(column,exceldata,excelName)
        } else {
        getAllListData({
          tableName: this.tableName
        }).then((res) => {
          if (res.code === 0) {
            let exceldata = res.data.map((item, serial) => {
              let data = {}
              this.fields.map((key, index) => {
                let value = item[key.name]
                let tag = this.tagIconsMap.get(key.name)?.tag
                if (this.specialTypes.includes(tag)) {
                  value = this.getShowValue(value, tag, this.tagIconsMap.get(key.name).dataType, this.tagIconsMap.get(key.name).option)
                } else if (tag=== 'datetime') {
                  value = this.getDateTime(value)
                } else if (tag === 'upload') {
                  value = this.getFile(value)
                } else if (tag === 'email') {
                  value = [value]
                } else if (tag === 'rich-text') {
                  value = this.getTinymce(value)
                }
                data[key.name] = value
              })
              return data
            })
            let column = []
            this.fields.map((item,index)=>{
              let temp = {}
              let tag = this.tagIconsMap.get(item.name)?.tag
              temp['title'] = item.desc
              temp['key'] = item.name
              if(tag === 'upload' && this.isImage || tag === 'email'){
                temp['type'] = 'image'
                temp['width']= 300,
                temp['height']= 300
              }else{
                temp['type'] = 'text'
              }
              column.push(temp)
            })
            const excelName = `${this.formName}`
            table2excel(column,exceldata,excelName)

            

            // let cols = []
            // let header = {
            // //   id: '序号'
            // }
            //  this.fields.map((key) => {
            //   header[key.name] = key.desc
            // })
            // header['create_time'] = '创建时间'
            // let exceldata = res.data.map((item, serial) => {
            //   let data = {
            //     // 'id': serial + 1
            //   }
            //   cols.push({
            //     wch: 30
            //   })
            //   this.fields.map((key, index) => {
            //     let value = item[key.name]
            //     let tag = this.tagIconsMap.get(key.name).tag
            //     if (this.specialTypes.includes(tag)) {
            //       value = this.getShowValue(value, tag, this.tagIconsMap.get(key.name).dataType, this.tagIconsMap.get(key.name).option)
            //     } else if (key.format === 'datetime') {
            //       value = this.getDateTime(value)
            //     } else if (key.tag === 'upload') {
            //       value = this.getFileNames(value)
            //     }
            //     data[key.name] = value
            //     cols.push({
            //       wch: 30
            //     })
            //   })
            // //   data['create_time'] = this.getDateTime(item.create_time)
            //   cols.push({
            //     wch: 30
            //   })
            //   return data
            // })
            // 新建空workbook，然后加入worksheet
            // const ws = XLSX.utils.json_to_sheet([header, ...exceldata], {
            //   skipHeader: true
            // })
            // // 设置每列的列宽，10代表10个字符，注意中文占2个字符
            // ws['!cols'] = cols
            // // 新建book
            // const wb = XLSX.utils.book_new()
            // // 生成xlsx文件(book,sheet数据,sheet命名)
            // XLSX.utils.book_append_sheet(wb, ws, this.formName)
            // // 写文件(book,xlsx文件名称)
            // XLSX.writeFile(wb, `${this.formName}.xlsx`)
          }
        }).catch(e => console.log(e))
        }
      },
      
      // exportToExcel(row,position) {
      //   if (position === 'inline') {
      //     let cols = []
      //       let header = {
      //       //   id: '序号'
      //       }
      //       this.fields.map((key) => {
      //         header[key.name] = key.desc
      //       })
      //       // header['create_time'] = '创建时间'
      //         let data = {
      //           // 'id': 1
      //         }
      //         cols.push({
      //           wch: 30
      //         })
      //         this.fields.map((key, index) => {
      //           let value = row[key.name]
      //           let tag = this.tagIconsMap.get(key).tag
      //           if (this.specialTypes.includes(tag)) {
      //             value = this.getShowValue(value, tag, this.tagIconsMap.get(key.name).dataType, this.tagIconsMap.get(key.name).option)
      //           } else if (key.format === 'datetime') {
      //             value = this.getDateTime(value)
      //           } else if (tag === 'upload') {
      //             value = this.getFileNames(value)
      //           }
      //           data[key.name] = value
      //           cols.push({
      //             wch: 30
      //           })
      //         })
      //       //   data['create_time'] = this.getDateTime(row.create_time)
      //         cols.push({
      //           wch: 30
      //         })
      //       // 新建空workbook，然后加入worksheet
      //       const ws = XLSX.utils.json_to_sheet([header, ...[data]], {
      //         skipHeader: true
      //       })
      //       // 设置每列的列宽，10代表10个字符，注意中文占2个字符
      //       ws['!cols'] = cols
      //       // 新建book
      //       const wb = XLSX.utils.book_new()
      //       // 生成xlsx文件(book,sheet数据,sheet命名)
      //       XLSX.utils.book_append_sheet(wb, ws, this.formName)
      //       // 写文件(book,xlsx文件名称)
      //       XLSX.writeFile(wb, `${this.formName}.xlsx`)
      //   } else {
      //   getAllListData({
      //     tableName: this.tableName
      //   }).then((res) => {
      //     if (res.code === 0) {
      //       let cols = []
      //       let header = {
      //       //   id: '序号'
      //       }
      //        this.fields.map((key) => {
      //         header[key.name] = key.desc
      //       })
      //       // header['create_time'] = '创建时间'
      //       let exceldata = res.data.map((item, serial) => {
      //         let data = {
      //           // 'id': serial + 1
      //         }
      //         cols.push({
      //           wch: 30
      //         })
      //         this.fields.map((key, index) => {
      //           let value = item[key.name]
      //           let tag = this.tagIconsMap.get(key.name).tag
      //           if (this.specialTypes.includes(tag)) {
      //             value = this.getShowValue(value, tag, this.tagIconsMap.get(key.name).dataType, this.tagIconsMap.get(key.name).option)
      //           } else if (key.format === 'datetime') {
      //             value = this.getDateTime(value)
      //           } else if (key.tag === 'upload') {
      //             value = this.getFileNames(value)
      //           }
      //           data[key.name] = value
      //           cols.push({
      //             wch: 30
      //           })
      //         })
      //       //   data['create_time'] = this.getDateTime(item.create_time)
      //         cols.push({
      //           wch: 30
      //         })
      //         return data
      //       })
      //       // 新建空workbook，然后加入worksheet
      //       const ws = XLSX.utils.json_to_sheet([header, ...exceldata], {
      //         skipHeader: true
      //       })
      //       // 设置每列的列宽，10代表10个字符，注意中文占2个字符
      //       ws['!cols'] = cols
      //       // 新建book
      //       const wb = XLSX.utils.book_new()
      //       // 生成xlsx文件(book,sheet数据,sheet命名)
      //       XLSX.utils.book_append_sheet(wb, ws, this.formName)
      //       // 写文件(book,xlsx文件名称)
      //       XLSX.writeFile(wb, `${this.formName}.xlsx`)
      //     }
      //   }).catch(e => console.log(e))
      //   }
      // },
      //搜索
      searchChange() {
         this.searchFormData = reorganizationParam(this.searchForm)
        // 修改搜索时从第一页开始
        this.page.pageNo = 1
        this.tableLoading = true
        this.getTableData()
      },
      //重置搜索
      searchReset() {
        // this.$refs.multipleTable.clearSort();
        this.processStatus = ''
        this.searchFormData = {}
        this.searchForm = {}
        this.datetime = []
        this.searchBox = false;
        // this.datetimeUpdate = []
        this.tableLoading = true
        this.getTableData()
        this.$nextTick(()=>{
          this.searchBox = true;
        })
      },
      //多选，数据选择改变
      handleSelectionChange(val) {
        this.$nextTick(() => {
          this.multipleSelection = val.filter(item => {
            return item.isSelect
          })
        })
      },
      //多选rowkey
      getRowKeys(row) {
        return row.id
      },
      //关闭标签
      closeTag() {
        this.$store.dispatch('tagsView/delView', this.$route).then(({
          visitedViews
        }) => {
          this.toLastView(visitedViews, this.$route)
        })
      },
      //跳转到上一页
      toLastView(visitedViews, view) {
        const latestView = visitedViews.slice(-1)[0]
        if (latestView) {
          this.$router.push(latestView.fullPath)
        } else {
          if (view.name === 'Dashboard') {
            this.$router.replace({
              path: '/redirect' + view.fullPath
            })
          } else {
            this.$router.push('/')
          }
        }
      },
      //判断是否固定列
      getFixed(index) {
        let left = this.rightConfig.colConfig.leftCol
        let right = this.rightConfig.colConfig.rightCol
        let showIndex = this.rightConfig.colConfig.showIndex
        let isFixed = false
        if (index < this.fieldData.length / 2) {
          if (left > 1) {
            if (showIndex) {
              isFixed = left - 2 > index ? 'left' : false
            } else {
              isFixed = left - 1 > index ? 'left' : false
            }
          }
        } else {
          if (right > 2) {
            if (this.showApproval) {
              isFixed = left - 3 > this.fieldData.length - index - 1 ? 'right' : false
            } else {
              isFixed = left - 2 > this.fieldData.length - index - 1 ? 'right' : false
            }
          }
        }
        return isFixed
      },
      //时间戳转日期时间
      getDateTime(time) {
        if (!time) return ''
        let date = new Date(time)
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let hour = date.getHours()
        let minute = date.getMinutes()
        let second = date.getSeconds()
        return `${year}-${month<10?'0':''}${month}-${day<10?'0':''}${day} ${hour<10?'0':''}${hour}:${minute<10?'0':''}${minute}:${second<10?'0':''}${second}`
      },
      //密码隐藏
      getPassword(data) {
        if (!data) return ''
        let str = ''
        for (let i = 0; i < data.length; i++) {
          str += '*'
        }
        return str
      },
      //富文本转纯文本
      getTinymce(val){
        if (val != null && val != '') {
            let str = val.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi,'[图片]')
            str = str.replace(/<video [^>]*src=['"]([^'"]+)[^>]*>/gi,'[视频]')
            str = str.replace(/<\/?.+?\/?>/g,'')
            // let str = val.replace(/<\/?.+?\/?>|\r|\n|&nbsp;/g,'')
            return str;
        } 
      },
      //每页条数改变
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
        this.page.pageNo = 1
        this.tableLoading = true
        this.getTableData()
      },
      //页码改变
      currentChange(current) {
        this.page.pageNo = current
        this.tableLoading = true
        this.getTableData()
      },
      //更改排序
      changeSort({column,prop,order}){
        if (order) {
           this.fieldName = prop
           this.order = order === 'descending' ? 'desc' : 'asc'
        } else {  //初始默认排序
           this.fieldName = this.oldfieldName
           this.order = this.oldorder
        }
        this.page.pageNo = 1
        this.tableLoading = true
        this.getTableData()
      },
      searchLabel (value, str) {
        for (let a = 0; a < this.tableDataOriginal.length; a++) {
            const rng = this.tableDataOriginal[a]
            if (rng.data_id + '' === value + '') {
                str = rng[this.rightConfig.treeConfig.childrenParams]
                return str
            }
        }
      },
      //特殊类型组件数据展示
      getShowValue(data, tag, dataType, options, params) {
        if (data + '' !== '0' && !data) {
          return ''
        } //空数据
        if (tag === 'switch') {
          if (options.length > 1) {
                return data === options[0]?.toString() ? '是' : (data === options[1]?.toString() ? '否' : '')
            } else {
                return ''
            }
        } else if (tag === 'checkbox' || tag === 'select' || tag === 'radio') {
          if (dataType === 'static') {
            if(/^\d+$/.test(data)){
             data = '' + data;
            }
            let keys = data.split(',')
            if (keys.length > 1 && tag === 'radio') {
              return ''
            } else {
              let str = []
              options.length > 0 && keys.map((res, index) => {
                options.forEach((item) => {
                  if (item.value.toString() === res || item.label.toString()===res) {
                    str.push(item.label)
                    return true
                  }
                })
              })
              return str.join(',')
            }
          } else {
            return data
          }
        } else if (tag === 'cascader' || tag === 'tree-table') {
          // 适配数据导入时用户使用 / 符号来分隔
          let keys = data.indexOf('/') !== -1 ? data.split('/') : data.split(',')
          if (dataType === 'dynamic') {
            return keys.join('/')
          } else if (dataType === 'static') {
            let str = []
            let index = 0
            keys.length > 0 && this.getLabelByKey(options, keys, index, str)
            return str.join('/')
          } else if (dataType === 'region') {
            let str = []
            let index = 0
            keys.length > 0 && this.getLabelByKey(this.regionDataCopy, keys, index, str)
            return keys.length > 0 ? str.join('/') : data.join('/')
          }

        } else if (tag === 'tree') {
            if (this.rightConfig.panelType === 'tree-list') {
                // 下拉树形组件
                let strLabel = ''
                strLabel = this.searchLabel(data, strLabel)
                return strLabel
            } else {
                this.loopSetKeyLabel(options)
                let strLabel = this.treeKeyAndLabelMap.get(data)
                return strLabel
            }
        }else if (['depart'].includes(tag)) {
            if (data) {
                const list = (data+'').split(',')
                let newList = []
                list.forEach(cur => {
                    let tempObjTemp = this.departAllList.find((item)=>{
                        return cur + ''=== item.id + '' || cur + ''=== item.name + '';
                    });
                    if (tempObjTemp) {
                        newList.push(tempObjTemp.name)
                    }
                })
                return newList.join(',')
            }
            return ''
        }
      },
      loopSetKeyLabel (options) {
        options.forEach(item => {
            this.treeKeyAndLabelMap.set(item.value + '', item.label)
            item.children && this.loopSetKeyLabel(item.children)
        })
      },
      //上传组件获取文件名
      getFileNames(data) {
        if (!data) {
          return ''
        } //空数据
        if (!this.isJson(data)) {
          return ''
        }
        let files = JSON.parse(data)
        return files.map((item) => {
          return item.name
        }).toString()
        // if (files?.length > 0) {
        //     return '文件'
        // }
      },

      //文件类型判断
      isAssetTypeAnImage(ext) {
        return ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].
        indexOf(ext.toLowerCase()) !== -1;
      },
       //上传组件获取文件
      getFile(data) {
        if (!data) {
          return ''
        } //空数据
        if (!this.isJson(data)) {
          return ''
        }
        let files = JSON.parse(data)
        // console.log('data',data,files)
        return files.map((item) => {
          // console.log(item.url)
          var index= item.url.lastIndexOf(".");
          var ext = item.url.substr(index+1);
          if(this.isAssetTypeAnImage(ext)){
            this.isImage = true
          }else{
            this.isImage = false
          }
          return item.url
        })
      },
      //根据key值获取label
      getLabelByKey(options, key, index, str) {
        options?.length > 0 && options.forEach((item) => {
          if (item.value.toString() === key[index] || item.label === key[index]) {
            str.push(item.label)
            index++
            index < key.length && this.getLabelByKey(item.children, key, index, str)
            return true
          }
        })
      },
      //根据key值获取value
      getValueByKey(options, key, index, str) {
       options && options.length > 0 && options.forEach((item) => {
          if (item.value.toString() === key[index] || item.label === key[index]) {
            str.push(item.value)
            index++
            item?.children && index < key.length && this.getValueByKey(item.children, key, index, str)
            return true
          }
        })
      },
      //获取所有字段的tag、dataType、option
      async getTagIcons(data) {
        if (data.length === 0) return
        let comps = data.filter((item) => {
          return item.__config__.tag !== 'TitleLine' //过滤标题和分割线组件
        })
        for (const item of comps) {
        //   let item = comps[i]
          if (item.__config__.tag === 'el-card' || item.__config__.tag === 'el-tabs' || item.__config__.tag === 'Steps'|| item.__config__.tag === 'el-collapse') {
            //布局组件，遍历内部子组件
            const newList = item.__config__.children
            for (const curComp of newList) {
               await this.getTagIcons(curComp.__config__.children)
            }
          } else if (item.__config__.tag === 'Subform') {
            const newList = item.__config__.children[0].__config__.children
            for (const newComp of newList) {
                await this.getTag(newComp, 'Subform')  // 子表单用map字段映射存值
            }
          } else {
             await this.getTag(item, 'form')
          }
        }
      },
      async getTag (item, flag) {
        let tag = item.__config__.tagIcon
        let options = []
        if (tag === 'switch') {
            options = [item['active-value'], item['inactive-value']]
            const obj = {
                tag: tag,
                dataType: item.dataType,
                params: item.__vModel__,
                option: [...options],
                label: item.__config__.label
            }
            if (flag === 'form') {
                this.tagIconsMap.set(item.__vModel__, obj)
            } else {
                this.tableTagIconsMap.set(item.__vModel__, obj)
            }
        } else if (['coding','select', 'radio', 'checkbox', 'tree'].includes(tag)) {
            if (item.dataType === 'static') { //静态数据
                options = item.options
                const obj = {
                    tag: tag,
                    dataType: item.dataType,
                    params: item.__vModel__,
                    option: [...options],
                    label: item.__config__.label
                }
                if (flag === 'form') {
                    this.tagIconsMap.set(item.__vModel__, obj)
                } else {
                    this.tableTagIconsMap.set(item.__vModel__, obj)
                }
            } else if (item.dataType === 'dictionary' && item.dictName !== '') { //字典数据
                let res = await getDictData({
                    dictType: item.dictName
                })
                if (res.code === 0) {
                    res.data.forEach((item) => {
                      //注
                        options.push({
                            label: item.label,
                            value: item.value
                        })
                    })
                }
                const obj = {
                    tag: tag,
                    dataType: item.dataType,
                    params: item.__vModel__,
                    option: [...options],
                    label: item.__config__.label
                }
                if (flag === 'form') {
                    this.tagIconsMap.set(item.__vModel__, obj)
                } else {
                    this.tableTagIconsMap.set(item.__vModel__, obj)
                }
            } else if (item.dataType === 'datasource' && item.tableName && item.fieldName && item.saveFieldName) { //动态数据源
                await sourceTestList(item.tableName).then(rsp => {
                    if (rsp.code === 0) {
                        let tempList = rsp.data?.rowMaps.map((itemTwo)=>{
                            return {
                                label: itemTwo[item.fieldName],
                                value: itemTwo[item.saveFieldName]
                            }
                        })
                        const obj = {
                            tag: tag,
                            dataType: item.dataType,
                            params: item.__vModel__,
                            option: [...tempList],
                            label: item.__config__.label
                        }
                        if (flag === 'form') {
                            this.tagIconsMap.set(item.__vModel__, obj)
                        } else {
                            this.tableTagIconsMap.set(item.__vModel__, obj)
                        }
                    }
                })
            }
            // else if (item.dataType === 'datasource' && item.dataSource && item.fieldName && item.saveFieldName) { //动态数据源 联想弹窗
            //     await sourceTestList(item.dataSource).then(rsp => {
            //         if (rsp.code === 0) {
            //             let tempList = rsp.data?.rowMaps.map((itemTwo)=>{
            //                 return {
            //                     label: itemTwo[item.fieldName],
            //                     value: itemTwo[item.saveFieldName]
            //                 }
            //             })
            //             const obj = {
            //                 tag: tag,
            //                 dataType: item.dataType,
            //                 params: item.__vModel__,
            //                 option: [...tempList],
            //                 label: item.__config__.label
            //             }
            //             if (flag === 'form') {
            //                 this.tagIconsMap.set(item.__vModel__, obj)
            //             } else {
            //                 this.tableTagIconsMap.set(item.__vModel__, obj)
            //             }
            //         }
            //     })
            // }
             else if (item.dataType === 'dynamic' && item.fields[0]?.tableName) {
                await sourceTestList(item.fields[0].tableName).then(rsp => {
                    if (rsp.code === 0) {
                        let tempList = rsp.data?.rowMaps.map((itemTwo)=>{
                            return {
                                label: itemTwo[item.fields[0]?.datas[0]?.showName],
                                value: itemTwo[item.fields[0]?.datas[0]?.fieldName]
                            }
                        })
                        const obj = {
                            tag: tag,
                            dataType: item.dataType,
                            params: item.__vModel__,
                            option: [...tempList],
                            label: item.__config__.label
                        }
                        if (flag === 'form') {
                            this.tagIconsMap.set(item.__vModel__, obj)
                        } else {
                            this.tableTagIconsMap.set(item.__vModel__, obj)
                        }
                    }
                })
            }
        } else if (tag === 'cascader'|| tag === 'tree-table') {
            if (item.dataType === 'dynamic') { //动态数据源
                sourceTestList(item.fields[0].tableName).then(rsp => {
                    if (rsp.code === 0) {
                        let tempList = rsp.data?.rowMaps.map((itemTwo)=>{
                            return {
                                label: itemTwo[item.fields[0]?.datas[0]?.showName],
                                value: itemTwo[item.fields[0]?.datas[0]?.fieldName]
                            }
                        })
                        const obj = {
                            tag: tag,
                            dataType: item.dataType,
                            params: item.__vModel__,
                            option: [...tempList],
                            label: item.__config__.label
                        }
                        if (flag === 'form') {
                            this.tagIconsMap.set(item.__vModel__, obj)
                        } else {
                            this.tableTagIconsMap.set(item.__vModel__, obj)
                        }
                    }
                })
            } else if (item.dataType === 'static'){ //静态数据
                options = item.options
                const obj = {
                    tag: tag,
                    dataType: item.dataType,
                    params: item.__vModel__,
                    option: [...options],
                    label: item.__config__.label
                }
                if (flag === 'form') {
                    this.tagIconsMap.set(item.__vModel__, obj)
                } else {
                    this.tableTagIconsMap.set(item.__vModel__, obj)
                }
            } else if (item.dataType === 'region') { //行政区域
                const obj = {
                    tag: tag,
                    dataType: item.dataType,
                    params: item.__vModel__,
                    option: [...this.regionDataCopy],
                    label: item.__config__.label
                }
                if (flag === 'form') {
                    this.tagIconsMap.set(item.__vModel__, obj)
                } else {
                    this.tableTagIconsMap.set(item.__vModel__, obj)
                }
            }
        } else { //其他普通组件
            const obj = {
                tag: tag,
                dataType: item.dataType,
                params: item.__vModel__,
                option: [...options],
                label: item.__config__.label
            }
            if (flag === 'form') {
                this.tagIconsMap.set(item.__vModel__, obj)
            } else {
                this.tableTagIconsMap.set(item.__vModel__, obj)
            }
        }
      },
      //获取子级选项
      getChildren(name, data, index,fields,tableData) {
        let option = []
        if (index >= fields.length) {
          return option
        } else {
          fields[index].datas.map((item) => {
            if (item.parent === name) {
              [...new Set(tableData.filter((field) => {
                return field[name] === data
              }).map((field)=>{return field[item.fieldName]}))].map((field) => {
                let node = {
                  label: field,
                  value: field
                }
                let child = this.getChildren(item.fieldName, field, index+1,fields,tableData)
                if (child.length > 0) {
                  node.children = child
                }
                option.push(node)
              })
            }
          })
          return option
        }
      },
      //数据格式化成对应数据库存储类型
      getFormatValue(data, tag, format) {
        if (!data && data !== 0) {
            return ''
        }
        if (arrTypes.includes(tag)) { //组件数据类型为数组
          return data.toString()
        }
        if (tag === 'upload') { //上传组件
          return typeof(data)=='string'?data:JSON.stringify(data)
        }
        if ((format === 'int' || format === 'double' || format === 'decimal') && !Number.isNaN(data)) { //数据库存储类型为int或double，但组件数据类型为字符串
          if(tag === "number"){
            return data!==''?data:''
          }
          return data!==''?Number(data):''
        }
        if (format === 'varchar') {
            if (Array.isArray(data)) {
                return data.join(',')
            }
            return data.toString()
        }
        return data
      },
      //判断是否是json
      isJson(str) {
        if (typeof (str) === 'string') {
          try {
            var obj = JSON.parse(str)
            if (typeof (obj) === 'object' && obj) {
              return true
            } else {
              return false
            }
          } catch (e) {
            return false
          }
        }
      },
      //将数据库存储类型转为组件数据类型
      setFormatValue(data, format, tag, options, dataType) {
        if (!data) { //空数据
          return data
        }
        if (format === 'datetime') {
          return this.getDateTime(data)
        }
        if (tag === 'upload') {
          if (this.isJson(data)) {
            return JSON.parse(data)
          } else {
            return []
          }
        }
        if (basicTypes.includes(tag)) {
          // if (format === 'double' && tag!=='number') {
          //   return data.toString()
          // } else {
          //   return data
          // }
          return data
        }
        if (['time-range','date-range','user','post','depart'].includes(tag)) {
            if (!data && data !== 0) {
                return ''
            } else {
                const valueList = (data + '').split(',')
                let resultValueList = []
                let tempList = 'depart' === tag ? this.departAllList : 'user' === tag ? this.allUserList : this.allPostList
                if ('depart' === tag || 'post' === tag) {
                  for (let a = 0 ;a < tempList.length;a++) {
                    const temp = tempList[a]
                    valueList.forEach(curVal => {
                      if (curVal === temp.id + '' ||  curVal === temp.name) {
                        resultValueList.push(temp.id)
                      }
                    })
                  }
                  return resultValueList
                } else if('user' === tag){
                    for (let a = 0 ;a < tempList.length;a++) {
                      const temp = tempList[a]
                      valueList.forEach(curVal => {
                          if (curVal === temp.id + '' || curVal === `${temp.nickname}/${temp.username}`) {
                              resultValueList.push(temp.id)
                          }
                      })
                    }
                    return resultValueList
                } else {
                    return (data + '').split(',')
                }
            }
        }
        if (tag === 'switch') {
          if (data === options[0].toString()) {
            data = options[0]
          } else if (data === options[1].toString()){
            data = options[1]
          }
          return data
        }
        if (tag === 'radio' || tag === 'select' || tag === 'coding') {
          let option = options.filter((item) => {
            if ((item.value??'') !== '' && (item.label??'') !== '') {
                return (item.value + '') === data || item.label + '' === data
            }
          })
          return option.length > 0 ? option[0].value : data
        }
        if (tag === 'checkbox') {
          let keys = data.split(',')
          let newKeys = keys.map((item,index) => {
            let option = options.filter((opt) => {
              return opt.value.toString() === item || opt.label.toString() === item
            })
            return option.length > 0 ? option[0].value : item
          })
          return newKeys || []
        }
        if (tag === 'cascader'|| tag === 'tree-table') {
          // 适配数据导入时用户使用 / 符号来分隔
          let tempkeys = data.indexOf('/') !== -1 ? data.split('/') : data.split(',')
           let tempstr = []
           let index = 0
           tag === 'tree-table' ? options = [...this.regionDataCopy] : options
           tempkeys.length > 0 && this.getValueByKey(options, tempkeys, index, tempstr)
           if(tag === 'cascader' && dataType === 'dynamic'){
             tempstr = tempkeys;
           }
           if(tag === 'tree-table'){
              tempstr = tempstr;
           }
           return tempstr
        }
        return data
      },
      //提交表单数据
      submit(data, valueMap) {
        const tableValueList = []
        // 组装子表单数据批量插入
        if (valueMap.size > 0) {
          let subTable = []
            for (let [k, v] of valueMap) {
              if(this.status !== 'add'){
                const aa = this.changeobj.childTableStore
                subTable = this.changeobj?.childTableStore?.filter((item,index)=>{ 
                  return item.tableName === k
                })
              }
                v.forEach((params,index) => {
                    const obj = {}
                    obj.data = []
                    delete params.id
                    delete params.showComp
                    const keyLst = Object.keys(params)
                    keyLst.forEach(insideKey => {
                        const tempObj = {}
                        tempObj.type = this.tableFiledsMap.get(k + '-' + insideKey).format
                        tempObj.name = insideKey
                        tempObj.value = this.getFormatValue(params[insideKey], this.tableTagIconsMap.get(insideKey).tag, tempObj.type)
                        obj.data.push(tempObj)
                    })
                    if(this.status !== 'add') {
                      obj.data.push({ 
                        name: 'version_id',
                        type: 'TINYINT',
                        value: this.status === 'edit' ? this.changeobj?.version_id : this.changeobj?.version_id + 1,
                      })
                      if(subTable[0].data[index]?.data_id){
                        obj.data.push({
                        name: 'data_id',
                        type: 'BIGINT',
                        value: subTable[0].data[index].data_id,
                      })
                      }
                    }
                    if(this.status === 'edit') {
                      obj.data.push({
                        name: 'approve_status',
                        type: 'tinyint',
                        value: this.changeobj?.bpmStore.approve_status,
                      })
                    }
                    obj.tableName = k
                    obj.dataId = this.childCurrent
                    tableValueList.push(obj)
                })
            }
        }
        let fields = [],fieldNew = []
        let createObj = {},createObjNew = {}
        const _this = this
        this.fields.map((item, index) => {
          if (data[item.name] !== undefined && data[item.name] !== null) {
            let value = this.getFormatValue(data[item.name], _this.tagIconsMap.get(item.name)?.tag, item.format) //格式化数据，转化为数据库存储类型
                fieldNew.push({
                    name: item.name,
                    type: item.format,
                    value: value
                })
                createObjNew[item.name] = value
          }
        })
        this.fields.map((item, index) => {
            if (data[item.name] !== undefined && data[item.name] !== null) {
                // 数据值不改变不传值，勿删
                if (this.status !== 'add') {
                    let one = ''
                    let two = ''
                    if (Array.isArray(data[item.name])) {
                        one = data[item.name].join(',')
                    }
                    if (Array.isArray(_this.originData[item.name])) {
                        two = _this.originData[item.name].join(',')
                    }
                    if (one !== two || data[item.name] !== _this.originData[item.name]) {
                        let value = this.getFormatValue(data[item.name], _this.tagIconsMap.get(item.name).tag, item.format) //格式化数据，转化为数据库存储类型
                        fields.push({
                            name: item.name,
                            type: item.format,
                            value: value
                        })
                        createObj[item.name] = value
                    }
                } else {
                    let value = this.getFormatValue(data[item.name], _this.tagIconsMap.get(item.name).tag, item.format) //格式化数据，转化为数据库存储类型
                    fields.push({
                        name: item.name,
                        type: item.format,
                        value: value
                    })
                    createObj[item.name] = value
                }
            }
        })
        if(this.status === 'change') {  //变更
              fieldNew.push({
                name: 'version_id',
                type: 'TINYINT',
                value: this.changeobj?.version_id + 1,
              })
              fieldNew.push({
                name: 'data_id',
                type: 'BIGINT',
                value: this.changeobj?.data_id+'',
              })
               const dataInsert = {
                 sysFromInsertDataVo: {
                  tableName: this.tableName,
                  dataType: '2',
                  repeatVerifyList: Array.from(this.repeatVerifySet),
                  data: fieldNew,
               },
               sysFromInsertDataVoList: tableValueList
              } 
              insertdataall(dataInsert).then((res) => {
                if(res.code === 0){
                  let obj = {}
                  this.fields && this.fields.forEach((cur) => {
                    obj[cur.name] = this.getFormatValue(data[cur.name], _this.tagIconsMap.get(cur.name).tag, cur.format)
                  })
                  let childForm = {
                    childTables: this.changeobj.childTables
                  }
                  createProcessInstance({
                      formId: this.formId,
                      formRecordId: res.data?res.data:'',
                      variables: {...obj,...childForm},
                      formStatus: 1 //变更
                    }).then(res => {
                        this.submitLoading = false
                        this.$message.success('变更成功 ')
                        this.dialogVisible = false
                        this.showForm = false
                        this.tableLoading = true
                        this.page.pageNo = 1
                        this.updateObj();
                        this.$refs.multipleTable.clearSelection()
                        this.getTableData()
                    }).catch(() => {
                        this.submitLoading = false
                    })
                }
              })
        }
        if (this.status === 'add') {  //新增
            let dataAll = {
               sysFromInsertDataVo: {
                  tableName: this.tableName,
                  dataType: '2',
                  repeatVerifyList: Array.from(this.repeatVerifySet),
                  data: fields
               },
               sysFromInsertDataVoList: tableValueList
            }
            insertdataall(dataAll).then((res) => {
                if(res.code === 0){
                  if (res.msg === '111') {
                        let errorList = []
                        res.data.forEach(itemField => {
                            errorList.push(this.fieldParamsMap.get(itemField).label)
                        })
                        this.submitLoading = false
                        this.$message.error(errorList.join(',') + ' 字段值已存在，不允许重复提交')
                    } else {
                      this.submitLoading = false
                      this.$message.success('新增成功')
                      this.dialogVisible = false
                      this.showForm = false
                      this.tableLoading = true
                      this.page.pageNo = 1
                      this.updateObj();
                      this.$refs.multipleTable.clearSelection()
                      this.handleOnload();
                      this.getTableData()
                    }
                }
            }).catch((e) => {
                this.submitLoading = false
                console.log(e)
            })
        } else if (this.status === 'edit') { //编辑
            let dataAll = {
               sysFromUpDataVo: {
                  tableName: this.tableName,
                  dataType: '2',
                  data: fields,
                  repeatVerifyList: Array.from(this.repeatVerifySet),
                  dataId: this.current
               },
               sysFromUpDataListVo: tableValueList
            }
            updataall(dataAll).then((res) => {
                if (res.code === 0) {
                    // 重复校验未通过
                    if (res.msg === '111') {
                        let errorList = []
                        res.data.forEach(itemField => {
                            errorList.push(this.fieldParamsMap.get(itemField).label)
                        })
                        this.submitLoading = false
                        this.$message.error(errorList.join(',') + ' 字段值已存在，不允许重复提交')
                    } else {
                        this.submitLoading = false
                        this.$message.success('更新成功')
                        this.dialogVisible = false
                        this.showForm = false
                        this.tableLoading = true
                        this.page.pageNo = 1
                        this.updateObj();
                        this.$refs.multipleTable.clearSelection()
                        this.handleOnload();
                        this.getTableData()
                    }
                }
            }).catch(() => {
                this.submitLoading = false
            })
        }
      },
      //按钮是否可点击
      canClick(name) {
        if (name === '发起审批'||name === '编辑'||name==='删除') {
          return !(this.multipleSelection.length === 1 && (this.multipleSelection[0].result ? this.multipleSelection[0].result===4||this.multipleSelection[0].result===5 : true))
        } else if (name === '导出'){
          return false
        } else {
          return !(this.multipleSelection.length === 1)
        }
      },
      getusersearch(val){
        if(val && !this.userList.length){
          this.searchPageNo = 1;
          this.getUserList();
        }
      },
      getpostsearch(val){
        if(val && !this.postList.length){
          this.searchPostPageNo = 1;
          this.getPostList();
        }
      },
      async getUserList(){
        let arr = await listUser({
            pageNo:this.searchPageNo,
            pageSize:10
        });
        this.userList.push(...arr.data.list);
        if(arr.data.list.length==10){
            this.searchPageNo++;
            this.getUserList();
        }else{
            this.searchPageNo = 1;
        }
      },
      async getPostList(){
        let arr = await listPost({
            pageNo:this.searchPostPageNo,
            pageSize:10
        });
        this.postList.push(...arr.data.list);
        if(arr.data.list.length==10){
            this.searchPostPageNo++;
            this.getPostList();
        }else{
            this.searchPostPageNo = 1;
        }
      },
      getdeptsearch(val){
        if(val && !this.deptList.length){
            listSimpleDepts().then(res=>{
              this.deptList = res.data;
          })
        }
      },
      handlerCommonValue(val,i){
        console.log(val,i,'handlerCommonValue')
        this.searchForm[i] = val;
      },
      updateObj(){
        if(this.formConfData.formType==='msgBox'){
          this.$refs.msgBoxParser.updateSubmitData();
        }else{
          this.$refs.parserRef.updateSubmitData();
        }
      }
    }
  }

</script>
<style lang="scss">
.delmarginTop{
  .el-dialog{
    margin-top: 0 !important;
  } 
  
}
.editTitle{
  margin-bottom: 20px;
  line-height: 48px;
  border-bottom: 1px solid rgba(0,0,0,0.10);
  width: 110;
  margin-left: -20px;
  margin-right: -20px;
  padding: 0 20px;
}
.treePart{
  overflow: hidden;
  margin-top: -20px;
  width: 245px;
  background: #ffffff;
  box-shadow: 4px 0px 4px 0px rgba(0,0,0,0.07); 
  min-height: calc(100vh - 104px);
  max-height: 100%;
  margin-left: -20px;
  .treeList{
    padding: 0 17px 0 20px;
    overflow: auto;
    max-height: 100%;
  }
  .el-input__inner{
    border-radius: 2px;
  }
  .title{
    font-size: 14px;
    font-family: PingFang SC, PingFang SC-Semibold;
    font-weight: 600;
    text-align: LEFT;
    color: #1890ff;
    line-height: 22px;
    margin: 25px 0 15px 0;
  }
}
.operationColumn{
  margin-bottom: 15px;
  float: right;
  .el-button--small{
    border-radius: 2px;
  }
}
.searchContent{
  .el-form-item{
    margin-bottom: 15px;
  }
  .el-date-editor.el-input, .el-date-editor.el-input__inner{
    width: 100%;
  }
  .el-input__inner{
    width: 260px;
    height: 32px;
    border: 1px solid #e1e1e1;
    border-radius: 2px;
  }
  .el-button--small{
    border-radius: 2px;
    padding: 9px 19px;
  }
}

.btnClassCss{
    padding:0 5px;
}
//修改复选框样式
  .indeterminate .el-checkbox__input .el-checkbox__inner {
    background-color: #409eff !important;
    border-color: #409eff !important;
    color: #fff !important;
  }

  .indeterminate .el-checkbox__input.is-checked .el-checkbox__inner::after {
    transform: scale(0.5);
  }

  .indeterminate .el-checkbox__input .el-checkbox__inner {
    background-color: #f2f6fc;
    border-color: #dcdfe6;
  }
  .indeterminate .el-checkbox__input .el-checkbox__inner::after {
    border-color: #c0c4cc !important;
    background-color: #c0c4cc;
  }
  .product-show th .el-checkbox__inner {
    display: none !important;
  }

  .indeterminate .el-checkbox__input .el-checkbox__inner::after {
    content: "";
    position: absolute;
    display: block;
    background-color: #fff;
    height: 2px;
    transform: scale(0.5);
    left: 0;
    right: 0;
    top: 5px;
    width: auto !important;
  }
  .product-show .el-checkbox__inner {
    display: block !important;
  }

  .product-show .el-checkbox {
    display: block !important;
  }

  .formManage {
    .tableInfo {
      .el-table__empty-block{
        border-bottom: 1px solid rgba(0,0,0,0.06);
        border-right: 1px solid rgba(0,0,0,0.06);
      }
      .el-table__header-wrapper th, .el-table__fixed-header-wrapper th{
        height: 48px;
      }
      .el-table__cell{
        height: 48px;
      }
      .el-table-column--selection .cell{
        padding-left: 0;
        padding-right: 0
      }
      .el-table__cell {
        border-bottom: 1px solid #dfe6ec;
        padding: 3px 0px;
      }
      .el-table__row {
        height: 40px !important;
      }
      .el-table__fixed {
        height: 100% !important;
      }

      .el-table__fixed-right {
        height: 100% !important;
      }

      .el-table__fixed::before {
        background-color: transparent;
      }

      .el-table__fixed-right::before {
        background-color: transparent;
      }
    }

    .el-table {
      box-sizing: border-box;

      &::before {
        height: 0px;
      }
    }

    .el-table--border::after,
    .el-table--group::after {
      width: 0px;
      height: 0px;
    }

    // 当前行高亮颜色
    // .current-row > td {
    //   background: #b2c8df !important;
    //   // color: white;
    // }

    // 鼠标悬浮行颜色
    // tr:hover > td {
    //   background-color: #b2c8df !important;
    // }
  }

</style>
<style lang="scss" scoped>
  .el-cascader-panel.is-bordered{
    border: none;
  }
  .el-cascader-menu {
    min-width: 150px;
  }
  .card-panel-group {
    width: 100%;
    margin-bottom: 10px;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;

    .card-panel {
      // width: 23%;
      // height: 108px;
      width: 260px;
      height: 100px;
      cursor: pointer;
      font-size: 12px;
      color: #666;
      background: #fff;
      box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
      border-color: rgba(0, 0, 0, .05);
      display: flex;
      align-items: center;
      margin-right: 20px;
      border-radius: 16px;
      // &:hover {
      //   .card-panel-icon-wrapper {
      //     color: #fff;
      //   }

      //   .icon-people {
      //     background: #40c9c6;
      //   }

      //   .icon-message {
      //     background: #36a3f7;
      //   }

      //   .icon-money {
      //     background: #f4516c;
      //   }

      //   .icon-shopping {
      //     background: #34bfa3
      //   }
      // }

      .icon-people {
        color: #40c9c6;
      }

      .icon-message {
        color: #36a3f7;
      }

      .icon-money {
        color: #f4516c;
      }

      .icon-shopping {
        color: #34bfa3
      }

      .card-panel-icon-wrapper {
        float: left;
        margin: 0px 14px;
        transition: all 0.38s ease-out;
        border-radius: 6px;
      }

      .card-panel-icon {
        float: left;
        font-size: 60px;
        padding: 10px;
        border-radius: 50%;
      }

      .card-panel-description {
        float: right;
        font-weight: bold;
        margin: 26px;
        margin-left: 0px;

        .card-panel-text {
          line-height: 18px;
          color: rgba(0, 0, 0, 0.45);
          font-size: 16px;
          // margin-bottom: 12px;
        }

        .card-panel-num {
          font-size: 20px;
        }
      }
    }
  }
.el-link{
  font-size: 12px;
}

</style>